Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally show a field in ASP.NET MVC Razor?

I am very new to C# and ASP.NET MVC Razor. I want to show a field in my view if the field is not blank.

Code

<tr class="hide" id="trPhone2">
            <td class="editor-label">
                @Html.LabelFor(model => model.phone2)
            </td>
            <td>
                @Html.EditorFor(model => model.phone2)
            </td>
            <td>
                @Html.ValidationMessageFor(model => model.phone2)
            </td>
        </tr>

Now, I want to output that first <tr> line if the model.phone2 is "" and else output:

<tr id="trPhone2">

How do I do this using ASP.NET MVC Razor?

like image 209
dmikester1 Avatar asked May 29 '13 12:05

dmikester1


People also ask

How do you write an if statement in a razor?

The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.

What is @model in razor?

New @model directive Let's now look at a new feature we added with the ASP.NET MVC 3 Beta – the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.

What is Razor syntax in MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

What is MVC Razor view?

Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC. Now, Razor Syntax is compact which minimizes the characters to be used, however it is also easy to learn.


2 Answers

The syntax might not be perfect, but try this:

    @{ 
        var trClass = string.IsNullOrEmpty(Model.phone2) ? "hide" : ""; 
    }

    <tr class="@trClass" id="trPhone2">
        <td class="editor-label">
            @Html.LabelFor(model => model.phone2)
        </td>
        <td>
            @Html.EditorFor(model => model.phone2)
        </td>
        <td>
            @Html.ValidationMessageFor(model => model.phone2)
        </td>
    </tr>
like image 102
gwin003 Avatar answered Sep 22 '22 07:09

gwin003


@if (string.IsNullOrEmpty(Model.phone2))
{
    <tr class="hide" id="trPhone2">
}
else
{
    <tr id="trPhone2">
}
like image 39
Andrei Avatar answered Sep 25 '22 07:09

Andrei