Search code examples
asp.net-mvcdynamicrazornamed-parametersroutevalues

Dynamic named parameter in route values collection using Razor view


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 &#9660;</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.


Solution

  • You haven't shown how the ActionLinkWithQueryString custom helper looks like but you could add an overload which takes a RouteValueDictionary instead of an anonymous object. And then it's easy:

    var values = new RouteValueDictionary();
    values["somedynamicname"] = "some dynamic value";
    values["someotherdynamicname"] = "some other dynamic value";
    

    and then:

    @Html.ActionLinkWithQueryString(fv.Range, "Search", values);
    

    Since you said that this is an extension method using ActionLink internally, there are overloads of ActionLink that take RouteValueDictionary instead of an anonymous object as route parameter.

    And since RouteValueDictionary has a constructor that takes a IDictionary<string, object> it could be very easy to build it using LINQ from your model.