Mis*_*ray 4 asp.net-mvc razor asp.net-mvc-5
我有一张桌子,上面的每个项目都有一个状态或状态,根据此状态,您可以购买项目或将其设置在等待列表中。
为此,我@if在 Razor 视图中有一条语句,在其中检查状态,然后有条件地选择要呈现哪个按钮来执行适当的操作。
我在会话和角色的其他视图中也有一些类似的逻辑。
这是一个好的做法吗?还有其他方法吗?
@if( @item.status == 1 ) {
<a class="btn btn-default" href="Items/Buy/@item.id">Buy</a>
} else if ( item.status == 2 ) {
<a class="btn btn-default" href="Items/SetList/@item.id">Add To List</a>
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这并不是世界上最糟糕的事情,因为它被用来在视图中显示元素。不过,我将为 HtmlHelper 创建一个扩展方法来呈现您尝试创建的操作链接。就像是:
public static class HtmlHelperExtensions
{
public static HtmlString RenderStatus(this HtmlHelper helper, ItemModel item)
{
if (item.status == 1)
{
return helper.ActionLink("Buy", "Buy", "Items", new { @class = "btn btn-default" });
}
if (item.status == 2)
{
return helper.ActionLink("Add To List", "SetList", "Items", new { id = item.Id }, new { @class = "btn btn-default" });
}
return new MvcHtmlString("");
}
}
Run Code Online (Sandbox Code Playgroud)
那么在您看来,您所需要做的就是致电
@Html.RenderStatus(item)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2257 次 |
| 最近记录: |