为此,您必须修改Html.Repeat
扩展方法以利用Phil Haack 所说明的Templated Razor Delegates 。进而:
@{Html.Repeat(
new[] { 5, 10, 20 },
@<text>
@if (item == Model.Search.PageSize)
{
<span>@item</span>
}
else
{
<a href="@Url.SetParameters(new { pagesize = item, page = 1 })">
@item
</a>
}
</text>,
@<text>|</text>
);}
更新:
根据您更新的问题,您似乎正在使用自定义 HTML 帮助程序,但正如我在回答中所述,如果您希望它工作,您需要更新此帮助程序以使用 Templated Razor Delegates 语法。例如,它的外观如下:
public static class HtmlHelperRepeatExtensions
{
public static void Repeat<T>(
this HtmlHelper html,
IEnumerable<T> items,
Func<T, HelperResult> render,
Func<dynamic, HelperResult> separator
)
{
bool first = true;
foreach (var item in items)
{
if (first)
{
first = false;
}
else
{
separator(item).WriteTo(html.ViewContext.Writer);
}
render(item).WriteTo(html.ViewContext.Writer);
}
}
}
或者如果你想让帮助方法直接返回一个 HelperResult ,这样你在调用它时就不需要使用方括号:
public static class HtmlHelperRepeatExtensions
{
public static HelperResult Repeat<T>(
this HtmlHelper html,
IEnumerable<T> items,
Func<T, HelperResult> render,
Func<dynamic, HelperResult> separator
)
{
return new HelperResult(writer =>
{
bool first = true;
foreach (var item in items)
{
if (first)
first = false;
else
separator(item).WriteTo(writer);
render(item).WriteTo(writer);
}
});
}
}
然后在你的视野内:
@Html.Repeat(
new[] { 5, 10, 20 },
@<text>
@if (item == Model.Search.PageSize)
{
<span>@item</span>
}
else
{
<a href="@Url.SetParameters(new { pagesize = item, page = 1 })">
@item
</a>
}
</text>,
@<text>|</text>
)