Search code examples
javascriptasp.netasp.net-mvcasp.net-mvc-5asp.net-routing

How to get routevalues from URL with htmlhelpers or JavaScript?


I have this MVC MapRoute

routes.MapRoute(
    name: "Authenticated",
    url: "{controller}/{action}/{foo}/{bar}",
    defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" }
);

And URL

http://localhost/mysite/controller/action/2/1

How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work as possible, because that would easially lead to alot of errors I think.

Note the URL might end with ?filter=xx sometimes, if it matters.

I have tryed

var foo= ViewContext.RouteData.Values["foo"];
var bar= ViewContext.RouteData.Values["bar"];

alert('foo: ' + foo);
alert('bar: ' + bar);

Result: e: ReferenceError: ViewContext is not defined


Solution

  • To write server side code to be processed by razor engine, you have to prepend your statement with @. That will only work if that Javascript is embedded on the view.

    You can also do it with Javascript. Something like this should do the trick

    var urlParts = location.href.split('/');
    var foo = urlParts[6];
    var bar = urlParts[7];