问题
I am trying to convert the popular asp.net MVC 2.0 solr.net sample app code to Razor syntax. I am not able to understand the last line ... Kindly help
<% Html.Repeat(new[] { 5, 10, 20 }, ps => { %>
<% if (ps == Model.Search.PageSize) { %>
<span><%= ps%></span>
<% } else { %>
<a href="@Url.SetParameters(new {pagesize = ps, page = 1})">@ps</a>
<% } %>
<% }, () => { %> | <% }); %>
[update] Source for Html.Repeat extension
HtmlHelperRepeatExtensions.cs
回答1:
For this to work you will have to modify the Html.Repeat
extension method to take advantage of Templated Razor Delegates as illustrated by Phil Haack. And then:
@{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>
);}
UPDATE:
According to your updated question you seem to be using a custom HTML helper but as I stated in my answer you need to updated this helper to use the Templated Razor Delegates syntax if you want it to work. Here's for example how it might look:
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);
}
}
}
or if you want to have the helper method directly return a HelperResult so that you don't need to use the brackets when calling it:
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);
}
});
}
}
and then inside your view:
@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>
)
回答2:
Possibly something like:
}, () => { <text>|</text> });
来源:https://stackoverflow.com/questions/11036496/translate-to-razor-syntax-from-mvc-2-0-code