Alex Rivera | Logout

Is there simple way how to join two RouteValueDictionary values to pass parameters to Html.ActionLink

Asked 2010-04-01T23:18:50.583
10

Look on my code that I created in a partial View:

<% foreach (Customer customerInfo in Model.DataRows) {%>

<tr>
    <td>
        <%=Html.ActionLink(
                customerInfo.FullName
                , ((string)ViewData["ActionNameForSelectedCustomer"])
                , JoinParameters(customerInfo.id, (RouteValueDictionary) ViewData["AdditionalSelectionParameters"])
                , null)%>
    </td>
    <td>
        <%=customerInfo.LegalGuardianName %>
    </td>
    <td>
        <%=customerInfo.HomePhone %>
    </td>
    <td>
        <%=customerInfo.CellPhone %>
    </td>
</tr>
<%}%>

Here I'm building simple table that showing customer's details.

As you may see, in each row, I'm trying to build a link that will redirect to another action.

That action requires customerId and some additional parameters.

Additional parameters are different for each page where this partial View is using. So, I decided to make Action methods to pass that additional parameters in the ViewData as RouteValueDictionary instance.

Now, on the view I have a problem, I need to pass customerId and that RouteValueDictionary together into Html.ActionLink method. That makes me to figure out some way of how to combine all that params into one object (either object or new RouteValueDictionary instance)

Because of the way the MVC does, I can't create create a method in the codebehind class (there is no codebehind in MVC) that will join that parameters.

So, I used ugly way - inserted inline code:

 ...script runat="server"...

private RouteValueDictionary JoinParameters(int customerId, RouteValueDictionary defaultValues)
{
    RouteValueDictionary routeValueDictionary = new RouteValueDictionary(defaultValues
Edit
Report

1 Answer

2

Perhaps a simple way to do accomplish this would be to create a UrlHelper extension that does something similar to what your JoinParameters method does. Something like the method below is a bit more reusable:

public static RouteValueDictionary AppendRouteValue(this UrlHelper helper, RouteValueDictionary routeValues, string key, object value)
{
    RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
    routeValueDictionary.Add(key, value);

    return routeValueDictionary;
}

Now your action like would be something like:

<%=Html.ActionLink(
    customerInfo.FullName
    , ((string)ViewData["ActionNameForSelectedCustomer"])
    , Url.AppendRouteValue((RouteValueDictionary) ViewData["AdditionalSelectionParameters"], "customerId", customerInfo.id)
    , null)%>
answered 2011-06-27T13:58:55.990

Your Answer