1

我需要在 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();
}
4

1 回答 1

1

我在 AssemblyQualifiedName 的帮助中使用 Type.GetType。它解决了问题。

var type = Type.GetType("AssemblyQualifiedName of my Type");

var properties = type.GetProperties();

谢谢威尔逊

于 2013-11-12T09:27:59.637 回答