If else logic in Razor DisplayFor vs TextBoxFor MVC4
asp.net-mvc-4, razor
Solution
Your Razor syntax is wrong, the correct syntax is (you don't need the surrounding `@{ }`):
@if (isFlagSet) {
@Html.TextBoxFor(m => m.HostpitalFinNumber)
@Html.ValidationMessageFor(m => m.HostpitalFinNumber)
}
else {
@Html.DisplayTextFor(m => m.HostpitalFinNumber)
}
The Html helpers don't write directly to the response (except the one which name's start with `Render`) so you need to use the `@` to write the generated HTML into the output.
Note that you don't need to set the value by hand with expression `new { @Value = Model.HostpitalFinNumber }` because the `Html.TextBoxFor` will take care of it.
Problem
If a certain variable is set I want a certain field to be a textbox, if it is not I want that field to simply display the value but that value is not editable. I put some if else logic into my views and the value won't display. Am I missing something here? ``` @{ if (isFlagSet) { Html.TextBoxFor(m => m.HostpitalFinNumber, new { @Value = Model.HostpitalFinNumber }); Html.ValidationMessageFor(m => m.HostpitalFinNumber); } else { Html.DisplayTextFor(m => m.HostpitalFinNumber); } } ``` Update... I changed my code to ``` @if (isFlagSet) { Html.TextBoxFor(m => m.HostpitalFinNumber); Html.ValidationMessageFor(m => m.HostpitalFinNumber); } else { Html.DisplayFor(m => m.HostpitalFinNumber); } ``` The following is the HTML being generated. Notice how an input value is being written for Phone but not hospital fin. Hot sure why that is happening. ``` <tr><td> <label for="Phone">Phone</label> </td> <td> <input Value="4124880798" id="Phone" name="Phone" type="text" value="4124880798" /> </td></tr> <tr><td> <label for="HostpitalFinNumber">HostpitalFinNumber</label> </td> <td> </td></tr> ``` ANSWER I forgot to put the @ in front of my html helper and get rid of the Semi-colons.