Jquery ajax call inside MVC
I work with a self made framework...开发者_JS百科I want to make an ajax call with jquery and I don't know how to pass the url...I mean if i have controller "categories" and action "index" the ajax call would be like this?
$.ajax({
type: "POST",
url: "http://localhost/learning/categories/index/",
});
How about this?
var controller = "categories";
var action = "index";
var myURL = "http://localhost/learning/" + controller + "/" + action + "/";
$.ajax({
type: "POST",
url: myURL
});
Is your JavaScript in an ASP.NET MVC view? If so, you can use Url.Action to generate the URL on the fly.
$.ajax({
type: "POST",
url: '<%: Url.Action("index", "categories")%>',
});
If your JavaScript is in a separate .js file, then you've added a bit more complexity.
My solution was to render the .js file dynamically (i.e. route scripts.js to an action method that returns a view with a contenttype of text/javascript).
I've also tried passing the URL from the rendered view to the .js file but this seemed messier than the above solution.
In MVC Conf on Tuesday, it was suggested that you simply avoid supporting both relative and absolute URLs - thus you could make assumptions about the base URL. That works too...
精彩评论