MVC Ajax action relative to current controller

北战南征 提交于 2019-12-24 15:33:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!