skip to Main Content

I am trying to send a partially filled object to my controller through an Ajax post.

var child =
{
    Property1: 1,
    Property2: 'test',
};
$.ajax({
    url: '/MyController/AddNewTest',
    type: 'POST',
    data: {"MyObject": child},
    success: function (data) {
    //Do stuff
    },
    error: function (data) {
    //Do stuff
    }
});

Controller:

[HttpPost]
public ActionResult AddNewTest(MyObject object)
{
//Do stuff
}

Object:

The object MyObject, has a lot of other properties, but in this case, I only need Property1 and Property2(I suspect that this may be the issue). Instead of sending two strings to my controller, I would prefer to pass this partially filled object, as this makes my life a bit easier down the road.

The problem is, that once the object arrives at my controller, everything inside the object is empty.

2

Answers


  1. Use below in the $.ajax

    contentType: 'application/json; charset=utf-8',
    

    due to missing the contentType it default takes

    'application/x-www-form-urlencoded; charset=UTF-8'
    

    So when you receive in controller everything inside the object is empty.

    Refer: https://api.jquery.com/jquery.ajax/

    Or Else Pass data as

    $("#btnsubmit").click(function (e) {   
            //Serialize the form datas.   
            var valdata = $("#friendform").serialize();   
            //to get alert popup   
            alert(valdata);   
            $.ajax({   
                url: "/Friend/AddFriend",   
                type: "POST",   
                dataType: 'json',   
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',   
                data: valdata   
            });   
        }); 
    

    for this refer: https://www.c-sharpcorner.com/article/asp-net-mvc-jquery-ajax-form-submit-using-serialize-form-data-into-a-model/

    Hope, you understand the problem.

    Login or Signup to reply.
  2.         url: '/MyController/AddNewTest',
            type: 'POST',
            data: JSON.stringify(child),
            processData: false,
            contentType: "application/json",
            dataType: "json",
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search