C# 如何从模型中获取所有属性名称?
我需要在HtmlHelper扩展中获取运行时为init的模型的所有属性名。我无法在helper中使用Type.GetType,因为它返回null 型号代码:C# 如何从模型中获取所有属性名称?,c#,asp.net-mvc,html-helper,C#,Asp.net Mvc,Html Helper,我需要在HtmlHelper扩展中获取运行时为init的模型的所有属性名。我无法在helper中使用Type.GetType,因为它返回null 型号代码: public class SampleVm { public object ResultObject { get; set; } public dynamic ResultDynamic { get; set; } } 查看代码: @Html.SampleResult(m => m. ResultDynamic)
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();
}
公共静态HtmlString搜索结果(此HtmlHelper html,
表达式(表达式)
{
TModel model=html.ViewData.model;
字符串属性名称=?????
//我想从ResultDynamic或ResultObject获取属性名称
//我可以在调试中找到ResultDynamic中的所有属性,但不知道如何使用
//获取它。对于ResultDynamic,我不知道如何获取属性名称。
返回新的HtmlString();
}
我在AssemblyQualifiedName的帮助中使用Type.GetType。它解决了问题
var type = Type.GetType("AssemblyQualifiedName of my Type");
var properties = type.GetProperties();
谢谢
Wilson我在AssemblyQualifiedName的帮助中使用Type.GetType。它解决了问题
var type = Type.GetType("AssemblyQualifiedName of my Type");
var properties = type.GetProperties();
谢谢
威尔逊