我正在尝试在表格中显示一些行。根据UserGroup,View应显示不同的标记。管理员可以删除行,但主持人只能将其标记为可见或不可见。
如何在Razor中编写正确的if else语句?
页面显示正确,但页面标题为分析错误
这是我的代码:
@model MvcApplication3.Models.ViewModels.New.Question.MatrixRows
@{
bool visible = Model.Visible;
}
<tr>
<td>
@if(visible)
{
@Html.TextBoxFor(cn => Model.Row_Number, new { @class = "row required digits", size = 1 })
}
@if (!visible)
{
@Html.TextBoxFor(cn => Model.Row_Number, new { @class = "row required digits", size = 1, disabled = "disabled" })
}
</td>
<td>
@if(visible)
{
@Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45 })
}
@if (!visible)
{
@Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45, disabled = "disabled" })
}
</td>
<td>
@if (HttpContext.Current.User.IsInRole("Administrator"))
{
@Html.HiddenFor(x => x.Delete, new { @class = "mark-for-delete" })
@Html.LinkToRemoveNestedForm("Slet", "tr", "input.mark-for-delete")
}
@if (HttpContext.Current.User.IsInRole("Moderator"))
{
@Html.HiddenFor(x => x.Visible, new { @class = "mark-for-visible" })
@Html.LinkToDisableNestedForm("Deaktiver", "tr", "input.mark-for-visible")
}
@Html.HiddenFor(id => Model.Row_Id)
</td>
</tr>
答案 0 :(得分:28)
标题有解析错误,因为您没有设置标题:
@{
ViewBag.Title = "Home Page";
}
现在,对于其他声明,请勿使用@
语法:
@if(visible)
{
Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45 })
}
else
{
Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45, disabled = "disabled" })
}
您正在检查布尔值,您只需要一个其他的。同样适用于else if
,它的工作原理相同。
只需执行以下操作即可简化您的代码:
@Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45, disabled = visible ? "" : "disabled" })
因为您正在显示相同的代码,只需根据值更改属性。对我来说,这变得更具可读性。
答案 1 :(得分:6)
因为问题是否则如果在剃刀中,我将其用于搜索引擎优化目的
视野
@{
if (ViewBag.Option == "Mobiles")
{
ViewBag.Title = "Mobiles";
ViewBag.Description = "Mobiles";
ViewBag.Keywords = "Mobiles";
}
else if (ViewBag.Option == "holiday")
{
ViewBag.Title = "holiday";
ViewBag.Description = "holiday.";
ViewBag.Keywords = "holiday";
}
else
{
ViewBag.Title = "home";
ViewBag.Description = "home";
ViewBag.Keywords = "home";
}
}
希望帮助某人。
答案 2 :(得分:4)
您只需使用else
而不添加@
。但是,我不认为这是您的页面标题的问题。也许您需要设置ViewBag.Title
属性?您的布局页面可能取决于它的设置。
@if(visible)
{
@Html.TextBoxFor(cn => Model.Row_Number, new { @class = "row required digits", size = 1 })
}
else
{
@Html.TextBoxFor(cn => Model.Row_Number, new { @class = "row required digits", size = 1, disabled = "disabled" })
}
标题问题:
@{
bool visible = Model.Visible;
ViewBag.Title = "My Title;
}