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.
-
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)
-
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)
-
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)
-
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)
-
@if (string.IsNullOrEmpty(Model.phone2))
{
<tr class="hide" id="trPhone2">
}
else
{
<tr id="trPhone2">
}
讨论(0)
- 热议问题