Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF ELSE html helper in razor view?

I will like to use IF ELSE statement in Razor view. Is it possible to use IF( html.helper ) 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>
like image 639
Edward.K Avatar asked Jun 01 '15 02:06

Edward.K


People also ask

What is HTML EditorFor in MVC?

ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.

What is the difference between HTML helpers and tag helpers?

Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.


1 Answers

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

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

The reason you wouldn't test against the value of DisplayFor is that it returns an MvcHtmlString, not just a simple type like a string or int. You could do something like this if you ever find the need to compare to a DisplayFor some day (and hopefully this makes it all make a little more sense):

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

Since you're in the process of learning MVC, you might also be interested in how you can customize the EditorFor helper to do this automatically: http://www.hanselman.com/blog/ASPNETMVCDisplayTemplateAndEditorTemplatesForEntityFrameworkDbGeographySpatialTypes.aspx

like image 77
Dave Ward Avatar answered Sep 28 '22 01:09

Dave Ward