Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

Posting JSON data via AJAX to Web API

I'm having trouble trying to pass a JSON object via AJAX POST request to Web API. Here is my AJAX POST request

<li><a href="#register">Register</a></li>

$('#usrRegister').click(function () {
    var uname = $('#usrName').val();
    var uloginname = $('#usrLoginName').val();
    var uemail = $('#usrEmail').val();
    var upwd = $('#usrPwd').val();

    var registerObj = {
        "name": uname,
        "username": uloginname,
        "email": uemail,
        "password": upwd
    };
    console.log("registerObj :", registerObj);

    $.ajax({                    
        url: "http://localhost:54118/api/UserApi",
        type: "POST",
        //contentType: "application/x-www-form-urlencoded",
        data: JSON.stringify(registerObj),
        contentType: "application/json",
        success: function (data) {
            alert("Successfully Registered..");
        },
        error: function (xhRequest, ErrorText, thrownError) {
            alert("Failed to process correctly, please try again");
        }
    });
 });

API :

[HttpPost]
public void Post(tblUser userdata)
{
    obj.tblUsers.Add(userdata);
    try
    {
        obj.SaveChanges();
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
    {
        foreach (var e in ex.EntityValidationErrors)
        {
            //check the ErrorMessage property
        }
    }
}

When I click register it is showing anonymous function at $.ajax({ in console and API is not calling. But when I replace contentType with application/x-www-form-urlencoded instead of application/json API is calling but showing all fields as null. When I call the same API in REST Client it is working fine. Help me what is causing issue.

Upvotes: 2

Views: 7394

Answers (2)

ermish
ermish

Reputation: 1270

Try adding the [FromBody] prefix to your parameter.

Like this: public void Post([FromBody] tblUser userdata).

Then, you should be able to use application/json again!

Upvotes: 3

Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

Thanks for reply. It's working with this code. I have added xhrFields: 'withCredentials:true' and contentType: 'application/x-www-form-urlencoded'

         $.ajax({                    
                    url: "http://localhost:54118/api/UserApi",
                    xhrFields: 'withCredentials:true',
                    type: "POST",
                    data: {
                                "name": uname,
                                "username": uloginname,
                                "email": uemail,
                                "password": upwd
                            },
                    contentType: 'application/x-www-form-urlencoded',
                    success: function (data) {
                        alert("Successfully Registered..");
                    },
                    error: function (xhRequest, ErrorText, thrownError) {
                        alert("Failed to process correctly, please try again");
                    }
                });

Upvotes: 4

Related Questions