如何使用 AJAX 将数据发布到 ASP.NET MVC 控制器?

Posted

技术标签:

【中文标题】如何使用 AJAX 将数据发布到 ASP.NET MVC 控制器?【英文标题】:How to post data to ASP.NET MVC controller using AJAX? 【发布时间】:2016-02-07 18:38:36 【问题描述】:

我想使用 jQuery AJAX 将 Mobile 数字和 EmailID 发送到我的 MVC 控制器,以检查这些详细信息是否已存在于数据库中。

当我在我的操作方法上使用[HttpPost] 属性时,我收到以下错误:

跨域请求被阻止:同源策略不允许读取 url 处的远程资源。

如果我删除 [HttpPost] 属性,我的操作方法将被调用,但在操作方法参数中收到的所有值都是 null

下面是动作方法代码:

public class LogOnModel

    public string Mobile  get; set; 
    public string EmailID  get; set; 


[HttpPost]
[AllowAnonymous]
///AJAXService/LogOnAjax
public ActionResult LogOnAjax(LogOnModel obj)

    return Json(true);

下面是我的 AJAX 调用:

var LoginModel = 
    'Mobile': "ASH",
    'EmailID': "MITTAL",
;
$.ajax(
    url: 'http://localhost:51603/AJAXService/LogOnAjax',
    type: 'GET',
    contentType: 'application/json',
    dataType: 'jsonp',
    data: JSON.stringify(LoginModel),
    success: function (result) 
        if (result == true) 
            window.location = "/Dashboard";
         else 
            $QuickLoginErrors.text(result);
        
    
);

我已将以下代码放在我的 web.config 文件中以避免 CORS 错误:

<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>

【问题讨论】:

如果您发布到自己的网站,我不会期望出现 CORS 错误。你能检查一下网址是否正确吗? 你看到了吗? ***.com/questions/6290053/… 【参考方案1】:

如果AjaxService 控制器与您正在处理的View 在同一个项目中:

var LoginModel = 
    Mobile: "ASH",
    EmailID: "MITTAL"
;

$.ajax(
    url: '@Url.Action("LogOnAjax","AJAXService")', // try to use Url Helper when possible
    type: 'POST', // use Get for [HttpGet] action or POST for [HttpPost]
    //contentType: 'application/json', not needed
    //dataType: 'jsonp', jsonp is for sending to a site other than the current one.. 
    data: LoginModel, // no need to stringify
    success: function (result) 
        if (result == true) 
            window.location = "/Dashboard";
         else 
            $QuickLoginErrors.text(result);
        
    
);

【讨论】:

不,我刚刚在一个简单的 test.html 文件中创建了这个 html 代码,然后通过 Chrome 浏览器打开了这个 html 文件。我的视图中没有此代码.. 非常感谢 Jamie...我刚刚在我的视图中添加了 AJAX 调用,之后一切都开始工作......再次感谢。【参考方案2】:

保留[HttpPost] 并将此行添加到您的$.ajax 行之前:

$.support.cors = true;

同时更改您的$.ajax 方法以匹配您的[HttpPost]。换行:

type: 'GET',

method: 'POST',

注意:这仅适用于我的 IE。 Chrome 仍然拒绝完成 Ajax 调用。不过,那是前一段时间的事了,我不确定新版本的 Chrome 是否可以使用这条线。

非常重要的注意事项:仅在开发中使用此行。不要使用此行编译您的应用程序。

【讨论】:

以上是关于如何使用 AJAX 将数据发布到 ASP.NET MVC 控制器?的主要内容,如果未能解决你的问题,请参考以下文章