Reputation: 3803
Can someone suggest how to use @URL.Action( "name", "controller", parameters} in your Jquery? Or atleat get the relative root to home directory.
I have to use JQuery get using the following code.
$(".ag").click(function () {
var id = this.id.replace("message_", "");
var cd = this.id.replace("message_", "display_message_");
$.get("/MRN/_Details_Message", function (data, status) {
document.getElementById(cd).innerHTML = "Data: " + data + "\nStatus: " + status;
});
});
The problem is that you cannot use @URL.Action
if your JS file is separate and if you google examples there are always complaints when using relative HTML paths with MVC.
Upvotes: 0
Views: 910
Reputation: 36113
I like to do the following, assuming "MRN" is your controller and "_Details_Message" is your action:
$.get('@Url.Action("_Details_Message", "MRN")', function (data, status) {
document.getElementById(cd).innerHTML = "Data: " + data + "\nStatus: " + status;
});
This will embed the root action into your javascript as "/MRN/_Details_Message" with the proper root prepended.
Upvotes: 0
Reputation: 100620
One approach is to pass url as parameter and render all interesting Urls as part of the page. Something like
On the page:
...var detailsUrl = '@Url.Action(....)';
In JavaScript:
$(".ag").click(function () {
var resultSelector = this.data("resultselector");
$.get(detailsUrl , function (data, status) {
$(resultSelector).html("Data: " + data + "\nStatus: " + status);
});
});
Upvotes: 0
Reputation: 13058
An easy solution is to put the url as an attribute of the relevant html element.
<a href="#" class="ag" data-url="@Url.Action("ActionName")">Click Here</a>
From within your jQuery code you can reference this easily:
$(".ag").click(function (e) {
var url = $(this).data("url");
});
Upvotes: 3
Reputation: 2037
I've ran into similar issues. If your JavaScript is in a different file (which I'm assuming), I just created a global function that kind of takes care of it, that is if you know the part of the relative path:
function getPath(p) {
var path = "";
if (window.location.href.indexOf("/MRN") > -1) {
path = "/MRN";
}
if (path.indexOf("/", path.length - 1) !== -1) {
return path + p;
} else {
return path + "/" + p;
}
}
Probably not the best solution, but it works for my projects.
Upvotes: 1
Reputation: 6684
I created a very simple MVC Controller to expose Routes that you need to access from javascript. You can find it at my GitHub -> https://github.com/tucaz/JSRouteController
Upvotes: 1