基于用户角色的ASP.NET MVC编辑器渲染EditorFor替代方案

9

我有一个基本的viewmodel类,其中包括一个当前用户属性,我需要MVC根据用户的管理员状态呈现文本框或标签。

目前,我这样做的方式是,但是代码必须重复很多次。

            @if (Model.CurrentUser.Admin)
            {
                @Html.EditorFor(m => m.Order.CustomerDiscount);
            }
            else
            {
                @Html.DisplayFor(m => m.Order.CustomerDiscount);
            }

是否可以创建自定义编辑器扩展?

            @Html.PrivilegedEditorFor(m=>m.Order.CustomerDiscount);

编辑:

感谢 @Fals。这里提供一个略微不同的解决方案:

using System.Web.Mvc.Html;
public static class HtmlHelperExtensions
{
    public static MvcHtmlString PrivilegedEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, bool isAdmin)
    {
        if (isAdmin)
        {
            return htmlHelper.EditorFor(expression);
        } else {
            return htmlHelper.DisplayFor(expression);
        }
    }

}
3个回答

8
您可以创建一个自定义的HTML Helper来实现此功能,例如:
1)在您的项目中添加一个新的类,这个类将包含该Helper。只需确保所使用的模型包含CurrentUser.Admin即可。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Helpers;
using System.Web.Mvc.Html;
using System.Linq.Expressions;

namespace MyAppName.Helpers
{
    public static class HtmlPrivilegedHelper
    {
        public static MvcHtmlString PrivilegedEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            // You can access the Model passed to the strongly typed view this way
            if (html.ViewData.Model.CurrentUser.Admin)
            {
                return html.EditorFor(expression);
            }

            return html.DisplayFor(expression);
        }
    }
}

2) 将命名空间添加到 Views 文件夹中的 Web.config 中,这样每次使用它时就不必再包含命名空间:

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="MyAppName.Helpers" /> //Here the helper reference
  </namespaces>
</pages>
</system.web.webPages.razor>

希望这能对您有所帮助!

1
好的,感谢您提供的表达细节。与此同时,我以更长的方式编写了这个帮助程序,并且无法像您一样简化它。首先,html.ViewData.Model.CurrentUser.Admin 部分无法确定,因为帮助程序方法只定义了模型作为一个简单对象。因此,我不得不传递一个名为 isAdmin 的布尔参数,这个帮助程序就不必查看模型来决定用户是否是管理员。 - Mehmet AVŞAR
其次,htmlHelper.EditorFor 部分对我无效,相反我不得不使用 System.Web.Mvc.Html.EditorExtensions.EditorFor(htmlHelper, expression)System.Web.Mvc.Html.DisplayExtensions.DisplayFor(htmlHelper, expression) - Mehmet AVŞAR

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接