我需要在 HtmlHelper 扩展中获取在运行时初始化的模型的所有属性名称。我不能在 helper 中使用 Type.GetType,因为它返回 null。
型号代码:
public class SampleVm
{
public object ResultObject { get; set; }
public dynamic ResultDynamic { get; set; }
}
查看代码:
@Html.SampleResult(m => m. ResultDynamic) // this is error, I don’t know why
@Html.SampleResult(m => m. ResultObject) // this works
控制器代码:
public ActionResult Index()
{
SearchVm vm = new SearchVm();
vm.ResultObject = Type.GetType("MvcApplication4.Models.Sample.SampleMasterModel");
vm.ResultDynamic = Type.GetType("MvcApplication4.Models.Sample.SampleMasterModel");
return View("Index", vm);
}
HtmlHelper 扩展代码:
public static HtmlString SearchResult<TModel, TProperty>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> expression)
{
TModel model = html.ViewData.Model;
String propertiesName = ?????
// I want to get the properties name from ResultDynamic or ResultObject
// I can found all properties from ResultDynamic in debug but don’t know how to
// get it. For ResultDynamic, I don't know how to get the properties name.
return new HtmlString();
}