MVC阿贾克斯后到控制器的操作方法 [英] MVC ajax post to controller action method

查看:293
本文介绍了MVC阿贾克斯后到控制器的操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找的问题在这里: MVC阿贾克斯JSON张贴到控制器但不幸的是它似乎并没有被帮我操作方法。我的是pretty的多少完全一样的,只是我的方法签名(但我已经试过了,它仍然没有得到命中)。

I've been looking at the question here: MVC ajax json post to controller action method but unfortunately it doesn't seem to be helping me. Mine is pretty much the exact same, except my method signature (but I've tried that and it still doesn't get hit).

$('#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
        }
    });
});

控制器

[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));
}

不过,无论我怎么努力,我的控制器从来没有被击中。经过调试,我知道,它发送一个请求,它只是得到了未找到误差各一次。

However, no matter what I try, my Controller never gets hit. Through debugging, I know that it sends a request, it just gets a Not Found error each time.

推荐答案

你的行动期望字符串参数,但是你发送一个复合对象。

Your Action is expecting string parameters, but you're sending a composite object.

您需要符合您所发送什么来创建一个对象。

You need to create an object that matches what you're sending.

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

public JsonResult Login(Data data)
{
}

修改

此外,toStringify()可能不是你想要的这里。只需发送对象本身。

In addition, toStringify() is probably not what you want here. Just send the object itself.

data: data,

这篇关于MVC阿贾克斯后到控制器的操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆