C# 如何判断传入自定义Html.DisplayFor helper的字段的类型?
如果我为助手编写自定义的C# 如何判断传入自定义Html.DisplayFor helper的字段的类型?,c#,asp.net-mvc,C#,Asp.net Mvc,如果我为助手编写自定义的显示,例如: public static HtmlString MyDisplayFieldFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData = null) { //... } 在Helper方法中
显示,例如:
public static HtmlString MyDisplayFieldFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, object additionalViewData = null)
{
//...
}
在Helper方法中访问此类型信息的最佳方式是什么?从表达式中获取值类型
public static HtmlString MyDisplayFieldFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, object additionalViewData = null) {
var valueType = typeof(TValue);
//...other code
}
公共静态HtmlString MyDisplayFieldFor(此HtmlHelper html,
表达式,对象additionalViewData=null){
var valueType=类型(TValue);
//…其他代码
}
您不需要检查传递值的类型。ASP.NET MVC允许您创建根据字段类型自动选择的字段
例如,您可以为示例中的SelectList
创建此模板,并将其放置在Views/Shared/DisplayTemplates/SelectList.cshtml
项目文件夹中
@model SelectList
<!-- Replace this with the display code you prefer -->
<div class="select-list">@Model.ToString()</div>
@model SelectList
@Model.ToString()
这使您可以在视图中保留HTML代码。获取TValue的类型,即typeof(TValue)
modelmetada metadata=modelmetada.FromLambdaExpression(expression,helper.ViewData)代码>然后元数据。ModelType
将为您提供类型
@model SelectList
<!-- Replace this with the display code you prefer -->
<div class="select-list">@Model.ToString()</div>