如何使用AJAX和JQuery将数据发布到ASP.NET MVC控制器
我想使用AJAX和jQuery向我的MVC控制器发送手机号码和emailID,以检查这些细节是否已经存在于数据库中。如何使用AJAX和JQuery将数据发布到ASP.NET MVC控制器
当我使用我的操作方法,然后我得到错误的[HttpPost]属性: - “跨来源请求阻止:同源策略不允许读取URL上的远程资源
如果我删除[HttpPost]属性,那么我的操作方法获取调用,但在行动方法参数接收到的所有值都为空。
以下是操作方法的代码。
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>
请帮忙如何使用AJAX后调用操作方法/获取一些数据 我新的ASP.NET MVC和挣扎了很多解决这个问题。
如果AjaxService控制器与您正在处理的视图位于相同的项目中。
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);
}
}
});
不,我刚刚创建了这个HTML代码在一个简单的test.html文件,然后通过Chrome浏览器打开这个html文件。我没有这个代码在我看来.. –
非常感谢杰米...我只是补充说,在我的观点,一切都开始工作后,AJAX电话.....非常感谢。 –
保持[HttpPost]
和你$.ajax
行前添加此行:
$.support.cors = true;
也能改变你$.ajax
方法,以配合您[HttpPost]
。更改行:
type: 'GET',
到
method: 'POST',
注意:这只能在IE中为我工作。 Chrome仍拒绝完成Ajax调用。但是,那是一段时间了,我不确定新版Chrome是否适用于这一行。
非常重要的注意事项:只有在开发中使用这条线。不要使用此行编译您的应用程序。
如果您发布到您自己的网站,我不会期望发生CORS错误。你能检查URL是否正确? –
你看到了吗? http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method – JamieD77