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>
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With