Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ajax post to controller action method

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).

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

Controller

[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.

like image 495
ediblecode Avatar asked Oct 29 '13 16:10

ediblecode


2 Answers

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)
{
}

EDIT

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

data: data,
like image 181
David L Avatar answered Oct 05 '22 18:10

David L


It's due to you sending one object, and you're expecting two parameters.

Try this and you'll see:

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

public JsonResult Login(UserDetails data)
{
   string error = "";
   //the rest of your code
}
like image 35
Chris Dixon Avatar answered Oct 05 '22 19:10

Chris Dixon