Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning value in razor difficulty

I am having the following pice of code which is firing error

Error 1 Invalid expression term '='

@{

  int Interest;

}

 <td>@if (@item.interest.HasValue)
    {

        @Interest= @item.interest.Value.ToString("F2");
    }
like image 319
learning Avatar asked Mar 03 '11 09:03

learning


2 Answers

When declaring a variable, this variable needs to be assigned:

@{
    string Interest = "";
}

and then:

@if (item.interest.HasValue)
{
    Interest = item.interest.Value.ToString("F2");
}

This being said doing something like this in a view is a very bad design. I mean things like declaring and assigning variables based on some condition is not a logic that should be placed in a view. The view is there to display data. This logic should go to your controller or view model.

like image 141
Darin Dimitrov Avatar answered Sep 18 '22 13:09

Darin Dimitrov


Inside your @if block you can address variables without the @ sign.

@if (@item.interest.value) {
   @item= @item.interest.Value
}

Is interpreted as:

@if (@item.interest.value) {
     Write(item=);
     Write(@item.interest.Value);
}

As you can see Write(item=) is not valid C# code.

You should use:

 @if (item.interest.value) {
     item = item.interest....
 }

The reason your if (@item....) statement compiles, with the @ sign. Is because you can prefix an identifier with the @ to use reserved words as identifier names.

like image 36
GvS Avatar answered Sep 19 '22 13:09

GvS