简体   繁体   中英

How to get only the Controller name and action name from URL with jQuery

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?

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];
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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM