asp.net-mvc-4asp.net-web-apiasp.net-ajaxasp.net-mvc-views

Posting value to web api method from ajax call why going null?


I am posting some values to web API method when I debug it's showing null values.

Below is a snipet code of ajax call, here I am passing dept_name but it's showing null in web API method.

var _customer = {};
            _customer.DepartmntName = txtName.val();
            _customer.DateCreated = null;
            _customer.DateModified = null;
            _customer.IsDeleted = null;
            _customer.ParentID = null;
            _customer.Icon = null;
            _customer.Paren = null;
            alert( _customer.DepartmntName);
            alert(_customer);
            $.ajax({
                type: "POST",
                url: "/api/AddDepSpc/InsertCustomer2",
                 data: JSON.stringify(_customer),
                contentType: "application/json",
                dataType: "json",
                success: function (r) {
                alert("success" + r);
               var row = $("#tblCustomers tr:last-child").clone(true);
                    //AppendRow(row, r.CustomerId, r.Name, r.Country);
      AppendRow(row,r.dept_name.r.date_created,r.date_modified,r.IsDeleted,
       r.ParentID.r.Icon,r.Paren);
                    txtName.val("");

                }
            });

Below snippet code for web api method.

public class AddDepSpcController : ApiController
    {
        [Route("api/AddDepSpc/InsertCustomer2")]
        [HttpPost]
        public   master_department InsertCustomer2(master_department _customer)
        {           
            using (HRMEntities entities = new HRMEntities())
            {
                entities.master_department.Add(_customer);
                entities.SaveChanges();
                entities.SaveChanges();
            }
            return _customer;
        }      
    }

Now in debug mode it shows null supposed I have passed HR as department name and all the rest of parameter are null now.Expecting HR parameter value in web api method.

Debug


Solution

  • Your posting back an object that contains property names that do not match your model.

    You model contains a property named dept_name, but the javascript object contains one named DepartmntName. Similarly, none of the other names match (except Icon). Assuming you want to bind the value of txtName to the models dept_name property, then in the script, use

    var _customer = {};
    _customer.dept_name = txtName.val(); // not DepartmntName
    ....
    

    Note also that there is no reason to add the null values to the _customer object (they will be null by default in the controller). You can also delete the contentType: "application/json", option and just use data: _customer, in the ajax call instead of stringifying it.