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

时间:2015-11-06 15:09:38

标签: c# jquery asp.net ajax asp.net-mvc

我想使用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]

2 个答案:

答案 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是否适用于此行。

非常重要的说明:仅在开发中使用此行。不要使用此行编译您的应用程序。

相关问题