简体   繁体   中英

Add a query string(s) at end of url using routes in ASP.NET MVC3

I want to add query string(s) to the end of an url using routes. How do I do this in Global.asax ?

routes.MapRoute(
    "Detail",
    "{controller}/{action}/{id}/{name}",
    new
    {
        action = "Detail",
        name = UrlParameter.Optional,
        // it is possible to add here query string(s) ?
    },
    new[] { "MyProject.Controllers" }
);

For example, the actual url contains:

www.mysite.com/MyController/Detail/4/MyValue

but I want to generate something like:

www.mysite.com/MyController/Detail/4/MyValue?ref=test&other=something

When you generate action URLs, you can pass in additional route values, like this:

@Url.Action("Detail", "MyController",
    new { id = 4, @ref = "test", other = "something" })

The ref and other parameters, which are not defined in the route template of the Detail route, will be appended as query string parameters.

MVC.NET automatically binds parameters from query string to your controller action input.

Example of your controller action would be like:

public ActionResult Detail(string id, string name, string test, string other){

}

Also, you can generate the link using a code like the following:

UrlHelper helper = new UrlHelper(HttpContext.Current.Request.RequestContext);
var url = helper.RouteUrl("Detail", new {id="testid", name="testname", ref="testref", other="testother"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM