The best solution is to use the Url.Action
or Url.RouteUrl
html helper method(s) to build the correct relative url to the action method. This will take care of building the correct url irrespective of the current page/view you are in.
var url1="@Url.Action("Create","Home")";
//use url1 now.
The above code will work if you have your javascript inside the razor views. If your script is inside an external file, You can build the relative url to the root and pass that to your js file and use that to build the url's as needed. Make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.
So in your razor view (Layout file or specific view), you may do this.
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
myApp.Urls.jobListUrl= '@Url.Action("Index","jobs")';
</script>
<script src="~/Scripts/YourExternalJsFile.js"></script>
And in your YourExternalJsFile.js
file, you can read it like
var urlToJobIndex= myApp.Urls.jobListUrl;
// Or With the base url, you may safely add the remaining url route.
var createUrl= myApp.Urls.baseUrl+"home/create";
Edit : If you simply care about getting the root/base url of the site so you can append that to get the other url you are after, you may simply use /
as the first character of your url.
var createUrl= "/home/create";
For your specific click event on an anchor tag use case, you can simply read the href
attribute value of your link and use that.
If you want to make the ajax call to the same action method as the href
attribute value of the link.
<a id="clickaroo" href="@Url.Action("Create","Customer")">Create<a/>
And in your click event get the href attribute value
$(function(){
$("#clickaroo").click(function(e){
e.preventDefault();
var u = $(this).attr("href");
$.post(u,function(response){
});
});
});
If you want to make the ajax call to the some other action method than the one in href attribute value of the link.
Here you can use data attribute to keep the other url in the link tag markup.
<a id="clickaroo" href="#" data-targurl="@Url.Action("Create","Customer")">Create<a/>
And in your click event get the data attribute value for "targurl"
$(function(){
$("#clickaroo").click(function(e){
e.preventDefault();
var u = $(this).data("targurl");
$.post(u,function(response){
});
});
});