I use a helper method to create sections in my view:
@helper CreateFacetSection(WebViewPage page, string sectionName,
List<FacetValue> model)
{
var showMore = int.Parse(WebConfigurationManager.AppSettings["ShowMore"]);
<section id="@sectionName">
<h4>@sectionName</h4>
<ul>
@for (int i = 0; i < model.Count(); i++)
{
if (i >= showMore)
{
@:<li class="hide">
}
else
{
@:<li>
}
FacetValue fv = model.ElementAt(i);
@page.Html.ActionLinkWithQueryString(fv.Range, "Search",
new { sectionName = fv.Range }, null);
@:(@fv.Count)
@:</li >
}
</ul>
@if(model.Count > showMore)
{
<a href="#" class="show-more" data-section="@sectionName">
@Localization.ShowMore ▼</a>
}
</section>
}
Now let’s say I have this custom @Html.ActionLink helper used in the helper above:
@Html.ActionLinkWithQueryString(fv.Range, "Search", new { sectionName = fv.Range });
Is there any way of passing a dynamic named parameter in the route value collection? In the case above I’d like to have a parameter sectionName dynamically named so that I’d get the correct value bound in the action method. It would vary according to the sectionName I’m currently passing as parameter to the helper method…
Right now I’m getting a link like this:
http://leniel-pc:8083/realty/search?sectionName=Volta%20Redonda
It should be:
http://leniel-pc:8083/realty/search?City=Volta%20Redonda
City or whatever I pass as parameter instead of sectionName because “City” is the value of the parameter sectionName I’m passing to the helper method.
I could do a switch for sectionName but I’m just wondering if there’s a neater way of achieving this.
You haven’t shown how the
ActionLinkWithQueryStringcustom helper looks like but you could add an overload which takes aRouteValueDictionaryinstead of an anonymous object. And then it’s easy:and then:
Since you said that this is an extension method using
ActionLinkinternally, there are overloads ofActionLinkthat takeRouteValueDictionaryinstead of an anonymous object as route parameter.And since
RouteValueDictionaryhas a constructor that takes aIDictionary<string, object>it could be very easy to build it using LINQ from your model.