基于 HtmlHelper 的自定義擴(kuò)展Container
Intro
基于 asp.net mvc 的權(quán)限控制系統(tǒng)的一部分絮重,適用于對(duì)UI層數(shù)據(jù)呈現(xiàn)的控制冤寿,基于 HtmlHelper
的擴(kuò)展組件
Code
基于 asp.net mvc 的權(quán)限控制系統(tǒng)示例代碼:https://github.com/WeihanLi/AccessControlDemo
權(quán)限控制核心代碼:https://github.com/WeihanLi/AccessControlDemo/tree/master/AccessControlHelper
SparkContainer 代碼:
public class SparkContainer : IDisposable
{
private readonly string _tagName;
private readonly ViewContext _viewContext;
private readonly bool _canAccess;
private bool _disposed;
private readonly string _content;
public SparkContainer(ViewContext viewContext, string tagName, bool canAccess = true)
{
_viewContext = viewContext;
_tagName = tagName;
_canAccess = canAccess;
if (!_canAccess)
{
_content = (_viewContext.Writer as StringWriter).GetStringBuilder().ToString();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
EndShopContainer();
}
}
public void EndShopContainer()
{
if (!_canAccess)
{
(_viewContext.Writer as StringWriter).GetStringBuilder().Clear().Append(_content);
}
else
{
_viewContext.Writer.Write("</{0}>", _tagName);
}
}
}
擴(kuò)展方法
/// <summary>
/// SparkContainer
/// </summary>
/// <param name="helper">HtmlHelper</param>
/// <param name="tagName">標(biāo)簽名稱</param>
/// <param name="attributes">htmlAttributes</param>
/// <param name="accessKey">accessKey</param>
/// <returns></returns>
public static SparkContainer SparkContainer(this HtmlHelper helper, string tagName, object attributes = null, string accessKey = "")
{
// ...
return SparkContainerHelper(helper, tagName, HtmlHelper.AnonymousObjectToHtmlAttributes(attributes), displayStrategy.IsControlCanAccess(accessKey));
}
private static SparkContainer SparkContainerHelper(this HtmlHelper helper, string tagName,
IDictionary<string, object> attributes = null, bool canAccess = true)
{
// ...
TagBuilder tagBuilder = new TagBuilder(tagName);
if (canAccess)
{
tagBuilder.MergeAttributes(attributes);
helper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
}
return new SparkContainer(helper.ViewContext, tagName, canAccess);
}
Use
使用說明:
@using(Html.SparkContainer("div",new { @class="container",custom-attribute = "abcd" }))
{
@Html.Raw("1234")
}
沒有權(quán)限訪問時(shí)就不會(huì)將內(nèi)容渲染到頁面,有權(quán)限訪問時(shí)實(shí)際渲染生成的 Html 如下:
<div class="container" custom-attribute="abcd">
1234
</div>
Contact
如果您有什么問題或建議青伤,歡迎與我聯(lián)系 weihanli@outlook.com