[英]How do I get all of the property names from a model?
我需要獲取HtmlHelper擴展中運行時初始化的模型的所有屬性名稱。 我不能在幫助器中使用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();
}
我在AssemblyQualifiedName的幫助中使用Type.GetType。 它解決了問題。
var type = Type.GetType("AssemblyQualifiedName of my Type");
var properties = type.GetProperties();
謝謝威爾遜
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.