我想使用 jQuery AJAX 将 Mobile
号码和 EmailID
发送到我的 MVC Controller ,以检查这些详细信息是否已存在于数据库中。
当我在我的操作方法上使用 [HttpPost]
属性时,出现如下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at url.
如果我删除 [HttpPost]
属性,将调用我的操作方法,但操作方法参数中收到的所有值都是 null
。
下面是 Action 方法代码:
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>
最佳答案
如果 AjaxService
Controller 与您正在处理的 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);
}
}
});
关于c# - 如何使用 AJAX 将数据发布到 ASP.NET MVC Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569786/