我有一个自定义助手“我的”,我想获得其中使用过的属性的值。
我这样称呼它:
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<VMThatHasAllTheseProps>" %>
<%=Html.My("Hi") %>
<%=Html.EditorFor(o => o.Prop) %> \\uses Html.My in the My.ascx template
<%=Html.My("[0].My") %>
<%=Html.My("[1].My") %>
和帮手:
public static MvcHtmlString My(this HtmlHelper html, string prop, object value = null)
{
//get value of the used property here
}
目前我喜欢这个:
//get val from model
if (value == null && html.ViewData.Model != null)
{
var p = TypeDescriptor.GetProperties(html.ViewData.Model).Find(prop, false);
if (p != null) value = p.GetValue(html.ViewData.Model);
}
//get val from model metada
if(value == null && html.ViewData.ModelMetadata != null)
{
var p = TypeDescriptor.GetProperties(html.ViewData.ModelMetadata.Model).Find(prop, false);
if (p != null) value = p.GetValue(html.ViewData.ModelMetadata.Model);
}
//get val from viewdata
if (value == null && html.ViewData.ContainsKey(prop))
value = html.ViewData[prop];
但显然它不适用于"[0].My"