Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何判断传入自定义Html.DisplayFor helper的字段的类型?_C#_Asp.net Mvc - Fatal编程技术网

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>