MVC dynamic routeValues for ActionLinks

getit picture getit · Nov 23, 2012 · Viewed 13.7k times · Source

I have a need to use ActionLink to link to ann edit screen for my ViewModel A.

A has a composite key, so to link to it, the route values will have to have 3 pramaters, like this:

<%: Html.ActionLink("EDIT", "Action", "Controller", 
    new { area = "Admin", Id1= 1, Id2= 2, Id3= 3 })%>

As you can see, the route values contain the ids that the controller Action will accept.

I want to be able to generate the route values from a helper function, like this:

public static Object GetRouteValuesForA(A objectA)
    {
        return new
        {
            long Id1= objectA.Id1,
            long Id2= objectA.Id2,
            long Id3= objectA.Id3
        };
    }

And then use it in the ActionLink helper, but I don't know how to pass that result to the ActionHelper

objectA = new A(){Id1= objectA.Id1,Id2= objectA.Id2,Id3= objectA.Id3};
....
<%: Html.ActionLink("EDIT", "Action", "Controller", 
    new { area = "Admin", GetRouteValuesForA(objectA) })%>

But that would need the controller action to accept that anonymous type instead of a list of 3 properties

I saw the below link that merges anonymous type, but is there any other way to do this? Merging anonymous types

Answer

Ant P picture Ant P · Nov 23, 2012

How about something like this?

Model:

public class AViewModel
{

    public string Id1 { get; set; }
    public string Id2 { get; set; }
    public string Id3 { get; set; }

    public RouteValueDictionary GetRouteValues()
    {
        return new RouteValueDictionary( new { 
            Id1 = !String.IsNullOrEmpty(Id1) ? Id1 : String.Empty,
            Id2 = !String.IsNullOrEmpty(Id2) ? Id2 : String.Empty,
            Id3 = !String.IsNullOrEmpty(Id3) ? Id3 : String.Empty
        });
    }
}

View:

<%: Html.ActionLink("EDIT", "Action", "Controller", Model.GetRouteValues())%>

You can now reuse them as much as you like and only ever have to change them in one place.