views:

133

answers:

1

I am trying to send the route values to a method but I cant seem to figure this out. Here is my code

<%  string s = "cool";
    object d = new {  s = "1" };

         %>
<%= Html.ActionLink("Home", "Index", d, "ql")%>

The following code produces a url like this

http://localhost:49450/?s=1

the url should be like this

http://localhost:49450/?cool=1

What am I missing

+1  A: 

because in the context of a 'new { ... }' expression the 's' does not correspond to a variable as it may first appear - it defines the name of a member of an anonymous class that is created.

when you say :

new { S = 123 }

you are actually generating a class, which is anonymous (you never get to see the name of the class). The type of each member of the class is implicitly determined by whatever you're assigning to it. In the above example a class something like this is generated

class AnonymousClass_S483Ks4 {
 public int S {get;set;}
}

There are two ways you can do what you want:

1) you would have to say :

new { cool = 123 } 

2) Now I assume though that you want the name to be dynamic so you need to use RouteValueDictionary which allows you to put key value pairs in.

        // RouteValueDictionary is IDictionary<string, object>
        var dictionary = new RouteValueDictionary();  
        string s = "cool";
        dictionary.Add(s, 123);
        htmlHelper.ActionLink("Home", "Index", dictionary);

As you can see, here you can use a variable 's' to represent whatever you want. This should give you the URL you need.

Simon_Weaver
Luke101
@luke101 based upon your original code are you possibly doing 'object dictionary = new RouteValueDictionary()' you need to make sure the object you pass to ActionLink() is of type RouteValueDictionary
Simon_Weaver
oh yes..I copied the code verbatim and tried it. But it gave the url above
Luke101
i ran it (I hadn't before) and got "<a href="/rrmvc/store/checkout?cool=123">Home</a>" which is what you're looking for. i've definitely had that problem you're having before and its caused by calling the wrong overload (where you pass in an 'object'). check which overload the compiler is using and make sure you're using the one with RouteValueDictionary. i'm using MVC2 but I don't think this signature has changed.
Simon_Weaver
you got this working right?
Simon_Weaver