How can I create a Html Helper like Html.BeginForm

后端 未结 1 590
忘了有多久
忘了有多久 2020-12-01 11:15

I have an Extension Method that verifies if the user is able to see a portion of the webpage, based on a Role.

If I simple remove the content, this brings me more wo

相关标签:
1条回答
  • 2020-12-01 11:48
    public static class HtmlExtensions
    {
        private class RoleContainer : IDisposable
        {
            private readonly TextWriter _writer;
            public RoleContainer(TextWriter writer)
            {
                _writer = writer;
            }
    
            public void Dispose()
            {
                _writer.Write("</div>");
            }
        }
    
        public static IDisposable RoleAccess(this HtmlHelper htmlHelper, string role)
        {
            var user = htmlHelper.ViewContext.HttpContext.User;
            var style = "display:none;";
            if (user.IsInRole(role))
            {
                style = "display:block;";
            }
            var writer = htmlHelper.ViewContext.Writer;
            writer.WriteLine("<div class=\"role_Content_General_Website\" style=\"" + style + "\">");
            return new RoleContainer(writer);
        }
    }
    

    and then you can use it like this:

    @using(Html.RoleAccess("Administrator"))
    {
        ...
    }
    

    You could obviously adapt the arguments of the helper to match your requirements:

    public static IDisposable RoleAccess(
        this HtmlHelper helper, 
        UserInfo user, 
        RoleAccessType role
    )
    {
        var style = "display:none;";
        if (user.HasAccess(role))
        {
            style = "display:block;";
        }
        var writer = htmlHelper.ViewContext.Writer;
        writer.WriteLine("<div class=\"role_" + role.ToString() + "\" style=\"" + style + "\">");
        return new RoleContainer(writer);
    }
    
    0 讨论(0)
提交回复
热议问题