如何在IEnumerable页面中使用自定义HtmlHelper?

时间:2022-04-12 05:49:35

My view page like this;

我的浏览页面是这样的;

@model IEnumerable<Project.ViewModels.ViewModel>
@using Helpers

@foreach (var item in Model)
{
    @Html.MyCustomHtmlHelper("test")
}

My custom HtmlHelper like this;

我的自定义HtmlHelper是这样的;

public static MvcHtmlString MyCustomHtmlHelper(this HtmlHelper helper, string TestValue)
{
    var builder = new StringBuilder();
    builder.Append(TestValue);

    return MvcHtmlString.Create(builder.ToString());
}

It works with @model Project.ViewModels.ViewModel but not @model IEnumerable<Project.ViewModels.ViewModel>

它适用于@model Project.ViewModels.ViewModel但不适用于@model IEnumerable

My error;

我的错误;

如何在IEnumerable页面中使用自定义HtmlHelper?

1 个解决方案

#1


1  

The code you have shown in your question:

您在问题中显示的代码:

@foreach (var item in Model)
{
    @Html.MyCustomHtmlHelper("test")
}

doesn't correspond to the code shown in the YSOD:

与YSOD中显示的代码不对应:

<td>
    @Html.MyCustomHtmlHelper(TestValue)
</td>

It looks like in your real code (which you haven't shown us), you have used some TestValue variable. Unfortunately it's pretty hard to know how/where/of what type is this variable declared but if it is not a string it is more than obvious that your custom helper won't work for the simple reason that this helper expects a string parameter.

它看起来像你的真实代码(你没有向我们展示),你已经使用了一些TestValue变量。不幸的是,很难知道这个变量声明的类型/地点/类型,但如果它不是一个字符串,那么你的自定义帮助器不会起作用,原因很简单,因为这个帮助器需要一个字符串参数。

#1


1  

The code you have shown in your question:

您在问题中显示的代码:

@foreach (var item in Model)
{
    @Html.MyCustomHtmlHelper("test")
}

doesn't correspond to the code shown in the YSOD:

与YSOD中显示的代码不对应:

<td>
    @Html.MyCustomHtmlHelper(TestValue)
</td>

It looks like in your real code (which you haven't shown us), you have used some TestValue variable. Unfortunately it's pretty hard to know how/where/of what type is this variable declared but if it is not a string it is more than obvious that your custom helper won't work for the simple reason that this helper expects a string parameter.

它看起来像你的真实代码(你没有向我们展示),你已经使用了一些TestValue变量。不幸的是,很难知道这个变量声明的类型/地点/类型,但如果它不是一个字符串,那么你的自定义帮助器不会起作用,原因很简单,因为这个帮助器需要一个字符串参数。