我想使用jQuery AJAX将EmailID
号码和[HttpPost]
发送到我的MVC控制器,以检查数据库中是否已存在这些详细信息。
当我在我的操作方法上使用[HttpPost]
属性时,我收到错误:
阻止跨源请求:同源策略禁止在URL处读取远程资源。
如果我删除了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);
}
。
以下是操作方法代码:
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);
}
}
});
以下是我的AJAX电话:
<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>
我已将下面的代码放在我的web.config文件中以避免CORS错误:
;with
cteClaims as (
SELECT a.LoanId, a.ID, a.ClaimType, a.ClaimStatus, a.ClaimTypeDescription
FROM [spd].[claims].[Population] a
GROUP BY a.LoanId, a.ID, a.ClaimType, a.ClaimStatus, a.ClaimTypeDescription
HAVING a.ClaimStatus not in ('Closed', 'Denied', 'Paid')),
ctePopulation as (
SELECT a.LoanId, a.ID, a.ClaimType, a.ClaimStatus, a.ClaimTypeDescription
FROM [spd].[claims].[Population] a
JOIN cteClaims b on a.LoanId = b.LoanId
GROUP BY a.LoanId, a.ID, a.ClaimType, a.ClaimStatus, a.ClaimTypeDescription)
SELECT loanid as cteLoanId
FROM [spd].[claims].[Population]
WHERE id in (select id from ctePopulation)
/// Error is here near this comma below
, cteLoanBase as (
select
a.LoanId as [Loan#]
, a.AcquisitionDt as [AcquisitionDt]
, a.CorpRecoverableBalanceAmt as [CorpRecoverableBalanceAmt]
, a.EscrowBalance as [EscrowBalance]
, a.FirstPaymentDueDt as [FirstPaymentDueDt]
, a.InvestorLoanId as [InvestorLoanId]
, a.InvestorPoolId as [InvestorPoolId]
, a.LoanStatusId as [LoanStatusId]
答案 0 :(得分:4)
如果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);
}
}
});
答案 1 :(得分:2)
保留[HttpPost]
并在$.ajax
行之前添加此行:
$.support.cors = true;
同时更改$.ajax
方法以匹配您的[HttpPost]
。改变这一行:
type: 'GET',
到
method: 'POST',
注意:这只适用于IE。 Chrome仍拒绝完成Ajax通话。但是,这是一段时间了,我不确定较新版本的Chrome是否适用于此行。
非常重要的说明:仅在开发中使用此行。不要使用此行编译您的应用程序。