[英]Why can't I use Html.DisplayNameFor in Razor functions section?
This is two pieces of code: 这是两段代码:
This is my model: 这是我的模特:
public class EnrollRequest
{
[Display(Name = "姓名")]
public string Name { get; set; }
[Display(Name = "性别")]
public Gender? Gender { get; set; }
// And other properties
}
I use this model for this page: 我在这个页面使用这个模型:
@model EnrollRequest
This one can pass compilation: 这个可以通过编译:
@{
System.Linq.Expressions.Expression<Func<EnrollRequest, string>> exp = item => item.Name;
Html.DisplayNameFor(exp);
}
But this one can't: 但是这个不能:
@functions
{
public MvcHtmlString DisplayData<EnrollRequest, TValue>(System.Linq.Expressions.Expression<Func<EnrollRequest, TValue>> exp)
{
return DisplayDataTable(Html.DisplayNameFor(exp), Html.DisplayFor(exp));
}
}
@helper DisplayDataTable(MvcHtmlString name, MvcHtmlString data)
{
<tr>
<th scope="row">@name</th>
<td>@data</td>
</tr>
}
It reports errors as follows on the first Html
: 它在第一个
Html
上报告错误如下:
'HtmlHelper<EnrollRequest>' does not contain a definition for 'DisplayNameFor' and the best extension method overload 'DisplayNameExtensions.DisplayNameFor<EnrollRequest, TValue>(HtmlHelper<IEnumerable<EnrollRequest>>, Expression<Func<EnrollRequest, TValue>>)' requires a receiver of type 'HtmlHelper<IEnumerable<EnrollRequest>>'
It seems that it requires an IEnumerable as the model but I actually don't have. 它似乎需要IEnumerable作为模型,但实际上我没有。 But the same call of
Html.DisplayNameFor
is valid in a helper. 但是
Html.DisplayNameFor
的相同调用在帮助Html.DisplayNameFor
是有效的。 What's the problem? 有什么问题?
=== ===
Edit: I invoke DisplayData like this: 编辑:我像这样调用DisplayData:
<table class="table">
<tbody>
@DisplayData(item => item.Name)
@DisplayData(item => item.Gender)
@DisplayData(item => item.School)
@DisplayData(item => item.Grade)
@DisplayData(item => item.Email)
</tbody>
</table>
And it asks me to specify the generic type for DisplayData because it failed to auto detect it. 它要求我为DisplayData指定泛型类型,因为它无法自动检测它。 Is there anything wrong?
有什么问题吗?
I've found what my problem is: 我发现了我的问题所在:
public MvcHtmlString DisplayData<EnrollRequest, TValue>(System.Linq.Expressions.Expression<Func<EnrollRequest, TValue>> exp)
{
return DisplayDataTable(Html.DisplayNameFor(exp), Html.DisplayFor(exp));
}
I accidentally wrote EnrollRequest
in the generic types that actually it doesn't need. 我不
EnrollRequest
在实际上不需要的泛型类型中编写了EnrollRequest
。 Just do this modification: 只需做这个修改:
public MvcHtmlString DisplayData<TValue>(System.Linq.Expressions.Expression<Func<EnrollRequest, TValue>> exp)
Then everything works fine. 一切正常。
Hope this can help someone. 希望这可以帮助别人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.