Unless otherwise, the logic in Razor DisplayFor vs TextBoxFor MVC4

If a specific variable is set, I want the specific field to be a text field, if that is not what I want this field to simply display the value, but this value is not editable.

I put some if else logic in my views and the value will not be displayed. Did I miss something?

@{ if (isFlagSet) { Html.TextBoxFor(m => m.HostpitalFinNumber, new { @Value = Model.HostpitalFinNumber }); Html.ValidationMessageFor(m => m.HostpitalFinNumber); } else { Html.DisplayTextFor(m => m.HostpitalFinNumber); } } 

Updating ...

I changed my code to

  @if (isFlagSet) { Html.TextBoxFor(m => m.HostpitalFinNumber); Html.ValidationMessageFor(m => m.HostpitalFinNumber); } else { Html.DisplayFor(m => m.HostpitalFinNumber); } 

Next, HTML is generated. Note how the input value is written for the phone, but not for the hospital fin. Hot sure why this 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 @ in front of my html helper and get rid of half-columns.

+4
source share
1 answer

The Razor syntax is incorrect, the correct syntax (you do not need the surrounding @{ } ):

 @if (isFlagSet) { @Html.TextBoxFor(m => m.HostpitalFinNumber) @Html.ValidationMessageFor(m => m.HostpitalFinNumber) } else { @Html.DisplayTextFor(m => m.HostpitalFinNumber) } 

Html helpers do not directly write the response (except for the name starting with Render ), so you need to use @ to write the generated HTML to the output file.

Note that you do not need to set the value manually using the expression new { @Value = Model.HostpitalFinNumber } , because Html.TextBoxFor will take care of this.

+9
source

Source: https://habr.com/ru/post/1440567/


All Articles