我有一个包含当前用户属性的基本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);
}
}
}
例如,您可以HTML Helper
为此创建一个自定义:
1)将new添加Class
到您的项目中,其中将包含帮助程序。只需确保使用的模型包含即可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)命名空间添加到Web.config
了在Views
文件夹中,那么你不必包括命名空间,你想用的时候:
<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>
希望这对您有所帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句