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

后端 未结 5 1043
逝去的感伤
逝去的感伤 2021-02-05 17:11

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



        
相关标签:
5条回答
  • 2021-02-05 17:28

    Simply wrap this field in if condition

    @if (Model.phone2=="")
    {
        <tr class="hide" id="trPhone2">
    }
    else
    {
        <tr 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>
    

    alternatively, you can simply skip the entire rendering of field like this

    @if (Model.phone2!="")
    {
    
        <tr 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>
    }
    

    Which is a better approach as it removes the field entirely from the dom object so removes any possibility of being edited later.

    0 讨论(0)
  • 2021-02-05 17:33

    I would calculate the class name in a code block and output that. Something along the lines of:

    @{
       var phone2ClassName = string.IsNullOrWhiteSpace(Model.phone2) ? "hide" : string.Empty;
    }
    
    <tr class="@phone2ClassName" id="trPhone2">
    ...
    
    0 讨论(0)
  • 2021-02-05 17:41

    If it is very complicated logic then use like this:

    var trId = "";
    if(Model[i].FeeType == (int)FeeTypeEnum.LateFee  
        || Model[i].FeeType == (int)FeeTypeEnum.WaivedFee)
    {        
        trId=String.Format("{0}_{1}", @Model[i].ProductId, @Model[i].FeeType);
    }
    else
    {
       trId = @Model[i].ProductId.ToString();
    }  
    
    
    <tr id="@trId" >  
    
    0 讨论(0)
  • 2021-02-05 17:48

    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>
    
    0 讨论(0)
  • 2021-02-05 17:49
    @if (string.IsNullOrEmpty(Model.phone2))
    {
        <tr class="hide" id="trPhone2">
    }
    else
    {
        <tr id="trPhone2">
    }
    
    0 讨论(0)
提交回复
热议问题