Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else logic in Razor DisplayFor vs TextBoxFor MVC4

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.

like image 340
SoftwareSavant Avatar asked Jan 16 '23 07:01

SoftwareSavant


1 Answers

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.

like image 171
nemesv Avatar answered Jan 19 '23 00:01

nemesv