我试图在表中显示一些行.根据UserGroup,视图应该显示不同的标记.管理员可以删除行,但主持人只能将其标记为可见或不可见.
如何在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,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,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","input.mark-for-visible") } @Html.HiddenFor(id => Model.Row_Id) </td> </tr>
解决方法
标题有解析错误,因为您没有设置标题:
@{ ViewBag.Title = "Home Page"; }
现在为了一个else语句,不要使用@语法:
@if(visible) { Html.TextBoxFor(bs => Model.Row_Description,size = 45 }) } else { Html.TextBoxFor(bs => Model.Row_Description,disabled = "disabled" }) }
你正在检查一个布尔值,你只需要一个别的.另外如果,它的工作原理相同.
您的代码可以通过以下方式进一步简化:
@Html.TextBoxFor(bs => Model.Row_Description,disabled = visible ? "" : "disabled" })