2

I am working on asp.net mvc4 and i am using razor for displaying data in my view.I am using one for loop in my view.my loop code is like below.

 **@for (int i = 0; i < 5; i++)
 {
    if (i<(@Html.DisplayFor(m => m.ProductInfo[5].Value)))
   {
     <img src="../../Images/star-on.png" />
   }
    else
    {
      <img src="../../Images/star-off.png" />
    }
  }**

In my above for loop in if condition i am trying to bind the number like 4.But it gives error like below

operator ' ' cannot be applied to operands of type 'int' and 'system.web.mvc.mvchtmlstring'

But when i display this razor code in my view like its showing the number "4".The code is like below.

@Html.DisplayFor(m => m.ProductInfo[5].Value)

1
  • i<(@Html.DisplayFor(m => m.ProductInfo[5].Value)) Why are you comparing a number to HTML? Why do you expect it to work? Is <span> greater than or equal to 6? Commented Sep 19, 2013 at 8:52

2 Answers 2

2

You need to check against the value not the display for the value

 @for (int i = 0; i < 5; i++)
 {
    if (i < Model.ProductInfo[5].Value)  @* <-- This line changed *@
   {
     <img src="../../Images/star-on.png" />
   }
    else
    {
      <img src="../../Images/star-off.png" />
    }
  }

Update

If your Model.ProductInfo[5].Value is of type string you need to do the following (providing you are not willing to change Value's type)

 @{
     int productFiveValue;
     bool canConvert = Int32.TryParse(Model.ProductInfo[5].Value, out productFiveValue);
 }
 @for (int i = 0; i < 5; i++)
 {
     if (canConvert && i < productFiveValue)
     {
         <img src="../../Images/star-on.png" />
     }
     else
     {
          <img src="../../Images/star-off.png" />
     }
 }
Sign up to request clarification or add additional context in comments.

5 Comments

mr NinjaNye Its now giving me the error like operator ' ' cannot be applied to operands of type 'int' and 'string'
Below your answer? I can't see it?
Is ProductInfo[5].Value of type string
i tried (i < Model.ProductInfo[5].Value).Count() it's giving me different value.
Glad to help. Please upvote or accept the answer if that is the case.
1

You don't need an HTML helper here, they usually return MvcHtmlString instances and you can't compare them to numbers. This should work:

if (i < Model.ProductInfo[5].Value)

4 Comments

mr NinjaNye Its now giving me the error like operator ' ' cannot be applied to operands of type 'int' and 'string'
@user2534261 What returns from Model.ProductInfo[5].Value?
it returns "4" number
@user2534261 as an int?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.