gpt4 book ai didi

c# - ASP.NET MVC 3 Razor DisplayFor Delegate

转载 作者:太空宇宙 更新时间:2023-11-03 13:56:33 27 4
gpt4 key购买 nike

我收到这个错误:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

这是我的代码(自定义 HTML 帮助程序,包装 DisplayFor 以便我可以选择模板):

public static string DisplayLocationTypeFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, LocationType>> expression, bool plural = false)
{
return plural ?
htmlHelper.DisplayFor(expression, "LocationTypePlural").ToHtmlString() :
htmlHelper.DisplayFor(expression).ToHtmlString();
}

当我这样使用它时,它起作用了:

@Html.DisplayLocationTypeFor(model => model.LocationType)

因为 model 有一个 LocationType 的属性。

但是当我在另一个自定义 HTML 帮助程序中执行此操作时:

public static MvcHtmlString SearchPreferenceButtonForModel<TModel>(this HtmlHelper<TModel> htmlHelper)
{
// .. other code
foreach (var property in htmlHelper.ViewData.ModelMetadata.Properties)
{
if (property.PropertyName == "LocationType")
htmlHelper.DisplayLocationTypeFor(model => ((LocationType)Enum.ToObject(typeof(LocationType), property.Model)), true);
}
}

它出错了。

我可以更改我的 DisplayLocationTypeFor 助手以使用 htmlHelper.Display,但我不确定如何。

有什么想法吗?

我正在尝试做的是我有一种特定的方式来呈现 LocationType 模型,我希望在整个网站上发生这种情况。在内部,该模板使用资源文件和其他一些基于 URL 的智能。换句话说,有逻辑 - 我不想重复。

这样,我所有的 View /模板都会调用此模板作为呈现 LocationType 的标准方式。

最佳答案

您需要阅读错误信息:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

它告诉您在 Razor 模板中只允许某些类型的(非常简单!)lambda 表达式。如果您有更复杂的东西,则需要在尝试将其传递给模板之前计算该值。这样的事情应该有效:

if (property.PropertyName == "LocationType") {
LocationType locationType = (LocationType) Enum.ToObject(typeof(LocationType), property.Model));
htmlHelper.DisplayLocationTypeFor(model => locationType, true);
}

关于c# - ASP.NET MVC 3 Razor DisplayFor Delegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11998537/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com