动作相对于电流控制器MVC阿贾克斯 [英] MVC Ajax action relative to current controller

查看:116
本文介绍了动作相对于电流控制器MVC阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从母版页的链接Ajax调用。

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.

 $.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?

推荐答案

如果你有这个直入你的看法,你可以做

If you got this straight into your view, you could do

 $.ajax({
      url: '@Url.Action("Save")',
      type: "GET",
      // .. etc 
 });

如果没有,JavaScript是在外部文件,您可以附加与<生成的URL href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action.aspx\"><$c$c>Url.Action以元素作为数据 - HTML5属性。然后做AJAX调用之前动态读取属性值。

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")" />

您应该的从不硬code网址在asp.net mvc的。始终使用 Url.Action 。生成URL时,永远返回根据它正确的值它检查你的路由配置。如果你硬code的URL,当您更改路由配置您的应用程序可能无法使用。你将不得不手动改变每一个URL在你的应用程序。

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.

这篇关于动作相对于电流控制器MVC阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆