问题
I'm trying to get an Ajax call from a link in a master page.
So I want to specify only the action relative to the current page/controller.
i.e.
$.ajax({
url: '/Save',
type: "GET",
// .. etc
});
I want to call the "Save" action of whatever controller served the page. I thought this would work straight off, but it doesn't appear to. Is there an elegant solution?
回答1:
If you got this straight into your view, you could do
$.ajax({
url: '@Url.Action("Save")',
type: "GET",
// .. etc
});
If not, and javascript is in external file, you could attach url generated with Url.Action to element as data-?
html5 attribute. And then dynamically read that attribute value before doing ajax call.
<input type="text" data-save-action-url="@Url.Action("Save")" />
You should never hardcode url's in asp.net mvc. Always use Url.Action
. It inspects your routing configuration when generating urls, and will always return correct value according to it. If you hardcode urls, your application may become unusable when you change routing configuration. And you will have to change every single url in you application manually.
来源:https://stackoverflow.com/questions/7609469/mvc-ajax-action-relative-to-current-controller