c# - 如何使用 AJAX 将数据发布到 ASP.NET MVC Controller ?

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

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

相关文章:

c# - 使用 EntityFramework : Context per Presenter or long conversation pattern for Windows Forms Applications?

javascript - 在 jQuery 中创建一个按钮

javascript - Drupal 和 Require.js 表现不佳 - jQuery 的双重加载

javascript - 如何通过循环查看多个元素样式的变化?

asp.net - 使用 FindControl : Accessing Controls in a Formview

c# - 基于端点的路由 .net core 3.1 中缺少端点

c# - 选择 gridview 行/单元格错误 "input string was not in correct format"

c# - 如何访问嵌套列表的键/值?

c# - 如何增加局部变量的限制

javascript - 当ASP.net仅返回名称时,在JS中通过ID选择控件