IF ELSE html helper in razor mode?

I would like to use the IF ELSE statement in the Razor view. Is it possible to use IF (html.helper) and then do something? Or any suggestion?

@using (Html.BeginForm()) { <table> @for (int i = 0; i < Model.Count; i++) { <tr> <td> @Html.HiddenFor(m => m[i].Question_ID) @Html.HiddenFor(m => m[i].Type) @Html.DisplayFor(m => m[i].Question) </td> </tr> <tr> @if(@Html.DisplayFor(m=> m[i].Type =="Info_Text") ** { <td> //DO NOTHING </td> } else { <td> @Html.EditorFor(m => m[i].Answer) </td> } </tr> } </table> 
+5
source share
2 answers

As I mentioned in my comment, you can directly check the value of m[i].Type :

 @if (m[i].Type == "Info_Text") { <td></td> } else { <td>@Html.EditorFor(m => m[i].Answer)</td> } 

The reason you won't test the DisplayFor value is because it returns an MvcHtmlString , not just a type of type string or int . You could do something like this if you ever find the need to compare with DisplayFor some day (and hopefully this will simplify everything):

 @if (Html.DisplayFor(m => m[i].Type) == new MvcHtmlString("Info_Text")) 

Since you are participating in the MVC learning process, you might also be wondering how you can configure the EditorFor to do this automatically: http://www.hanselman.com/blog/ASPNETMVCDisplayTemplateAndEditorTemplatesForEntityFrameworkDbGeographySpatialTypes.aspx

+4
source

Why should you use DisplayFor? Do you have any special reason?

How about if you use

 if(Model[i].Type =="Info_Text") { <td> //DO NOTHING </td> } 
+1
source

All Articles