Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send json object to the Controller Action method in MVC 4

I am trying to send my userid and password to my login Controller Action method.

//Login button click code

$("#btnLogin").click(function () {
    var userCrdential = {
        UserName: $("inputEmail3").val(),
        Password: $("inputPassword3").val()
    };
    $.ajax({
        type: "POST",
        url: "/Home/Login",
        content: "application/json; charset=utf-8",
        dataType: "json",
        data: userCrdential,
        success: function (res) {
          //  alert("data is posted successfully");
            if (res.success == true)
                alert("data is posted successfully");
            else {
               // alert("Something went wrong. Please retry!");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(xhr.statusMessage);
        }
    }); 
});

and in my home Controller I have login Action method

    [HttpPost]
    [ActionName("Login")]
    public ActionResult Login(User userCrdential)
    {
        string userIdtest = userCrdential.UserName;
        string userPasswordtest = userCrdential.Password;
        var result=false;

        if (userIdtest != null && userPasswordtest != null)
        {
             result = true;
        }
        else
        {
             result = false;
        }

        return Json(result);
        //return RedirectToAction("Index");
    }

but my action method is not invoking...

like image 742
Debashrita Avatar asked Dec 18 '25 05:12

Debashrita


1 Answers

You need to change content to contentType and call JSON.stringify on your data:

$.ajax({
    type: "POST",
    url: "/Home/Login",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(userCrdential),
    ...
}); 

See jQuery.ajax

like image 186
haim770 Avatar answered Dec 19 '25 19:12

haim770