Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 816
Snake Eyes Avatar asked Sep 26 '13 09:09

Snake Eyes


2 Answers

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.

like image 101
Marius Schulz Avatar answered Nov 14 '22 00:11

Marius Schulz


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"});
like image 2
Egor4eg Avatar answered Nov 14 '22 00:11

Egor4eg