开发者

How to dynamically create routes in a HTML actionlink

I am trying to send the开发者_如何学Python 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜