开发者

MVC Ajax action relative to current controller

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 c开发者_JAVA百科all 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜