MVC ajax发布到控制器动作方法

edi*_*ode 14 c# ajax asp.net-mvc jquery

我一直在看这里的问题:MVC ajax json发布到控制器动作方法但不幸的是它似乎没有帮助我.除了我的方法签名之外,我的几乎完全相同(但我已经尝试过了,但它仍然没有被击中).

jQuery的

$('#loginBtn').click(function(e) {
    e.preventDefault();

    // TODO: Validate input

    var data = {
        username: $('#username').val().trim(),
        password: $('#password').val()
    };

    $.ajax({
        type: "POST",
        url: "http://localhost:50061/checkin/app/login",
        content: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(data),
        success: function(d) {
            if (d.success == true)
                window.location = "index.html";
            else {}
        },
        error: function (xhr, textStatus, errorThrown) {
            // TODO: Show error
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

调节器

[HttpPost]
[AllowAnonymous]
public JsonResult Login(string username, string password)
{
    string error = "";
    if (!WebSecurity.IsAccountLockedOut(username, 3, 60 * 60))
    {
        if (WebSecurity.Login(username, password))
            return Json("'Success':'true'");
        error = "The user name or password provided is incorrect.";
    }
    else
        error = "Too many failed login attempts. Please try again later.";

    return Json(String.Format("'Success':'false','Error':'{0}'", error));
}
Run Code Online (Sandbox Code Playgroud)

但是,无论我尝试什么,我都Controller不会受到打击.通过调试,我知道它发送了一个请求,Not Found每次都会出错.

Dav*_*d L 16

您的Action需要字符串参数,但您正在发送复合对象.

您需要创建一个与您发送的内容相匹配的对象.

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}
Run Code Online (Sandbox Code Playgroud)

编辑

另外,toStringify()可能不是你想要的.只需发送对象本身.

data: data,
Run Code Online (Sandbox Code Playgroud)