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

radbyx
  • 9,352
  • 21
  • 84
  • 127

1 Answers1

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];
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • splitting the string is going to by far be the fastest , I don't see a problem with readability there at all – Scott Selby Jun 17 '15 at 19:46
  • I will try, looks fine at first glanse. Only worry would be if 6 and 7 would change – radbyx Jun 17 '15 at 19:51
  • Do you know how I can fix this? e: TypeError: location.split is not a function – radbyx Jun 17 '15 at 20:05
  • Use "window.location.href" instead of "location"? – radbyx Jun 17 '15 at 20:06
  • 1
    Fixed the mistake, please use location.href – Claudio Redi Jun 17 '15 at 20:06
  • I worked well. I am not thrilled about the hardcode indexies at all though. You don't have another solution without any hardcode values mate? :) – radbyx Jun 17 '15 at 20:10
  • @not of the top of my head. I'll update I come up with something. If the script is embedded on your view, you can check your initial solution fixing the syntax. It would fail the same if the rounte change though. – Claudio Redi Jun 17 '15 at 20:24
  • This only occur when I'm logged in. And for that I only have one route. It would have been nice if there was some helper where I only had to tell it my routename ("Authenticated"), and the (foo) and (bar), and then it somehow ceverly find and give me those values. You know what I mean? :) But thanks anyways, I'm implementing you're solution now. – radbyx Jun 18 '15 at 06:09