user2534261
user2534261

Reputation: 33

For loop issue in razor

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)

Upvotes: 2

Views: 225

Answers (2)

NinjaNye
NinjaNye

Reputation: 7126

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" />
     }
 }

Upvotes: 2

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

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)

Upvotes: 1

Related Questions