【发布时间】:2013-03-10 17:00:56
【问题描述】:
我打算为 MVC 创建一个扩展,如下所示:
public static class DivExtension
{
public static MvcHtmlElement BeginDiv(this HtmlHelper helper)
{
return new MvcDiv(helper.ViewContext).BeginDiv("","");
}
public static MvcHtmlElement BeginDiv(this HtmlHelper helper, string id)
{
return new MvcDiv(helper.ViewContext).BeginDiv(id,"");
}
}
在 Razor 中我可以这样使用它:
@{using(Html.BeginDiv())
{
<text>
This should appear inside a div <input type="text" value="oi" />
</text>
}
}
这将生成以下 HTML 输出:
<div>
This should appear inside a div <input type="text" value="oi" />
</div>
但是想象一下,我的代码不只是创建一个 div,而是接收一个代表角色的字符串,如果登录的用户不属于指定的角色,那么这个扩展中的 HTML 应该是压制:
public static class HtmlAuthSuppressor
{
public static MvcHtmlElement AuthHTML(this HtmlHelper helper, string roles)
{
//some code that would allow suppression
}
}
如果我这样使用:
<b>Do you see something below?</b>
@{using(Html.AuthHTML("Role_Super_User"))
{
<text>
Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" />
</text>
}
}
如果用户不属于指定角色,最终的 HTML 输出将是:
<b>Do you see something below?</b>
这可能吗?
更新: 我知道我可以生成这样的 HTML:
<b>Do you see something below?</b>
<!--
Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" />
--!>
但这会向客户透露一些我不想透露的信息,而且会使响应不必要地加重。
【问题讨论】:
标签: html asp.net-mvc razor extension-methods asp.net-authorization