How to send json object to Action Control method in MVC 4

I am trying to send my user id and password to my login 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 a login 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 doesn't call ...

+3


source to share


3 answers


You need to change content

to contentType

and call JSON.stringify

in your data:

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

      



See jQuery.ajax

+3


source


In MVC, you should never recode URLs.

Use instead @Url.Action

.

url: ('@Url.Action("Login", "Home")',

      

userCrdential

must be JSON encoded:



JSON.stringify(userCrdential)

      

Also, for the same your common sense, use the method fail

.

$.ajax("url")
    .done(function() {
    alert("success");
})
    .fail(function() {
    alert("error");
})

      

Last note, success

deprecated as jQuery 1.8

; you have to use done

.

0


source


Just change it:

var userCrdential = {
    UserName: $("inputEmail3").val(),
    Password: $("inputPassword3").val()
};

      

in

var userCrdential = "UserName=" + $("inputEmail3").val() + "&Password=" + $("inputPassword3").val();

      

everything else in the code is fine, but make sure your controller parameter has the same parameters as here, like UserName and Password.

however you need to validate user input before the ajax call.

0


source







All Articles