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

后端 未结 5 1045
逝去的感伤
逝去的感伤 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=="")
    {
        
    }
    else
    {
        
    }
                
                    @Html.LabelFor(model => model.phone2)
                
                
                    @Html.EditorFor(model => model.phone2)
                
                
                    @Html.ValidationMessageFor(model => model.phone2)
                
            
    

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

    @if (Model.phone2!="")
    {
    
        
            
                    @Html.LabelFor(model => model.phone2)
                
                
                    @Html.EditorFor(model => model.phone2)
                
                
                    @Html.ValidationMessageFor(model => model.phone2)
                
            
    }
    

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

提交回复
热议问题