4

I am using .net MVC in my website and I need to get the URL in javascript, but only the controller and action name, for instance if i have:

http://stackoverflow.com/questions/9513736/current-url-without-parameters-hash-https

I need:

http://stackoverflow.com/questions/9513736/

I have found some solutions such as:

urlBase = location.href.substring(0, location.href.lastIndexOf("/")+1)

->http://stackoverflow.com/questions/9513736/

However if my URL does not have any parameters I the action name is cut off like so:

http://stackoverflow.com/questions/

Does anyone have a solution for this?

3
  • Depends how consistent and reliable the URL will be. You could check to see if the URL ends with / if it does then don't substring it. That might work for you. Personally I would look to see if you can access the controller and action names through razor and write it directly to the javascript so you don't have to parse it. Commented Mar 9, 2015 at 16:07
  • URLS don't work like that; you only get the path. What happens after that is completely in your hands. Commented Mar 9, 2015 at 16:12
  • This is impossible without also duplicating all the route logic in JS. Instead, you probably want to have the server echo this data back via the payload for you to consume on the client. Commented Mar 9, 2015 at 16:13

2 Answers 2

22

You can use window.location.pathname for this.

For the url in this question it returns

"/questions/28946447/how-to-get-only-the-controller-name-and-action-name-from-url-with-jquery"

To read it properly you can use: window.location.pathname.split("/")
Read the value with:

var url = window.location.pathname.split("/");
var questions = url[1];
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this is my final solution: var manJSCmon = location.pathname.split("/"); var local = location.protocol + '//' + location.host + "/" + manJSCmon[1] + "/" + manJSCmon[2];
3
window.location.pathname;

this will return path from the url . then use split to get controller name and action name

var path=window.location.pathname;
var abc=path.split("/");
var controller=abc[0];
var action=abc[1] || "index";

Comments

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.