0

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

1
  • Oh it's razor i forgot the @{ } Commented Jun 17, 2015 at 19:43

1 Answer 1

2

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];
Sign up to request clarification or add additional context in comments.

8 Comments

splitting the string is going to by far be the fastest , I don't see a problem with readability there at all
I will try, looks fine at first glanse. Only worry would be if 6 and 7 would change
Do you know how I can fix this? e: TypeError: location.split is not a function
Use "window.location.href" instead of "location"?
Fixed the mistake, please use location.href
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.