我想清理我的代码
@foreach (System.Data.DataRowView c in (System.Data.DataView)ViewBag.Folders)
{
<tr>
@if ((Boolean)c.Row["VF_Visible"]) {
<td><a href="@Url.Action("Index", "page", new { parent = c.Row["SMF_VF_ID"], granParent = c.Row["VF_Parent_ID"] })">@c.Row["SMF_Name"]</a></td>
} else {
<td class="itemUnVisible"><a href="@Url.Action("Index", "page", new { parent = c.Row["SMF_VF_ID"], granParent = c.Row["VF_Parent_ID"] })">@c.Row["SMF_Name"]</a></td>
}
<td>@Html.ActionLink("Edit", "edit", new { id = c.Row["SMF_VF_ID"] })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = c.Row["SMF_VF_ID"] })</td>
<td>@Html.ActionLink("Preview", "Preview", new { id = c.Row["SMF_VF_ID"] })</td>
</tr>
}
if中的代码是重复的。
当我离开if而只是没有a标签的td和结束标签时,它会给我一个错误。
@foreach (System.Data.DataRowView c in (System.Data.DataView)ViewBag.Folders)
{
<tr>
@if ((Boolean)c.Row["VF_Visible"]) {
<td>
} else {
<td class="itemUnVisible">
}
<a href="@Url.Action("Index", "page", new { parent = c.Row["SMF_VF_ID"], granParent = c.Row["VF_Parent_ID"] })">@c.Row["SMF_Name"]</a></td>
<td>@Html.ActionLink("Edit", "edit", new { id = c.Row["SMF_VF_ID"] })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = c.Row["SMF_VF_ID"] })</td>
<td>@Html.ActionLink("Preview", "Preview", new { id = c.Row["SMF_VF_ID"] })</td>
</tr>
}
答案 0 :(得分:2)
你不能将非格式良好的HTML放在一个块中(例如你的<if>
),因为Razor不知道在哪里结束块。
您需要force the HTML to be treated as literal text:
@if ((Boolean)c.Row["VF_Visible"]) {
@:<td>
} else {
@:<td class="itemUnVisible">
}
答案 1 :(得分:0)
有一些不成文的规则表明,每次在视图中有if
时,请写一个帮助者:
public static HtmlString DetermineCellAction(this HtmlHelper helper,
object visibleColumnValue)
{
// All code below could be much cleaner, this is just an example!
var visible = (bool)visibleColumnValue;
var td = "";
td = (visible) ? "<td if visible>" : "<td if not visible>";
return new HtmlString(td);
}
然后你可以像使用它一样:
@foreach (System.Data.DataRowView c in (System.Data.DataView)ViewBag.Folders)
{
<tr>
@Html.DetermineCellAction(c.Row["VF_Visible"])
<!-- mode html here -->
</tr>
}
请注意,帮助程序是extension method,在这种情况下会扩展HtmlHelper
,但如果更方便的话,您也可以将其作为DataRowView
的扩展方法。
答案 2 :(得分:0)
你可以做类似的事情(未经测试)......
<td @if((bool)c.Row["VF_Visible"]) { <text>class="itemUnVisible"</text> } >
或
将ViewModel更新为比使用DataRowView集合更清晰。我将创建一个模型类,您可以在控制器中进行所有解析,包括计算可见性,然后将其传递给您的视图。
public class MyViewRecord
{
public int Id {get;set;}
public int ParentId {get;set;}
// etc.
public bool Visible {get;set;}
}
然后您可以执行类似......
的操作@foreach (MyViewRecord item in ViewBag.Folders)
{
<tr>
@if (item.Visible) {
<text><td></text>
} else {
<text><td class="itemUnVisible"></text>
}
<a href="@Url.Action("Index", "page", new { parent = item.ParentId, granParent = item.GrandParentId })">@item.Name</a></td>
<td>@Html.ActionLink("Edit", "edit", new { id = item.Id })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = item.Id })</td>
<td>@Html.ActionLink("Preview", "Preview", new { id = item.Id })</td>
</tr>
}
希望这有帮助