我在MVC中编写类似于DisplayFor
的扩展助手,但我的优点是它将从资源文件中检索实际的属性名称。
public class Gender
{
public int Id{get;set;}
public string Name{get; set;}
public string ArabicName{get;set;}
}
public class Employee
{
public int Id{get;set;}
public string Name{get;set;}
public string ArabicName{get;set;}
public Gender Gender{get;set;}
}
public static MvcHtmlString DisplayResourceFor<TModel, TValue>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TValue>> expression)
{
var rm = new ResourceManager("Resources.Global",
System.Reflection.Assembly.Load("App_GlobalResources"));
var property = ExpressionHelper.GetExpressionText(expression);
string resourceName = string.Empty;
var split = property.Split('.');
property = string.Empty;
// rebuild the expression taking the last name from the resource file
for (var index = 0; index < split.Length; index++)
{
if (index == split.Length - 1) // retrieve the data from rm
property += (string.IsNullOrWhiteSpace(property) ? "" : ".") + rm.GetString(string.Format("{0}Resource", split[index]));
else
property += (string.IsNullOrWhiteSpace(property) ? "" : ".") + split[index];
}
var value = helper.ViewContext.ViewData.GetViewDataInfo(property);
return value == null ? MvcHtmlString.Empty : MvcHtmlString.Create(value.Value.ToString());
}
上述代码不适用于
等复杂数据@Html.DisplayResourceFor(model =>model.Gender.Name)
我尝试使用ModelMetadata.FromStringExpression(property,helper.ViewData)
,但返回的值为空
我的代码中缺少什么部分?
任何帮助都将受到高度赞赏