MVC dynamic routeValues for ActionLinks
Asked Answered
K

1

5

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

Koblas answered 23/11, 2012 at 17:50 Comment(2)
Can't you just add the values as properties of your viewmodel?Seyler
They are, but I just want to use the function to generate the route values in case the definition of A changes, like if I need to add or remove Ids that make up the composite key. That way, I would only have to change the params in one placeKoblas
S
11

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.

Seyler answered 23/11, 2012 at 19:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.