A NewBie A NewBie - 19 days ago 10
Ajax Question

Nested javascript object properties are null when sent to the controller in MVC using AJAX

I have the following entities in my model.

public class Provider
{
public int ProviderId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SSN { get; set; }
public string NPI { get; set; }
public ProviderDetails ProviderDetails { get; set; }

}

public class ProviderDetails
{
public int ProviderDetailsId { get; set; }
public string Certification { get; set; }
public string Specialization { get; set; }
public string TaxonomyCode { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
public int ProviderId { get; set; }
}


I have the following controller action method.

[HttpPost]
public ActionResult CreateProvider(Provider provider)
{
try
{
int providerCreationSuccessful = _repository.CreateProvider(provider);
if (providerCreationSuccessful == 1)
TempData["userIntimation"] = "Provider Registered Successfully";

return RedirectToAction("ShowTheListOfProviders");
}
catch (Exception Ex)
{
_logger.Error(Ex.Message);
return View("Error");
}
}


I am sending data to the controller using AJAX as shown.

self.createProviderDetails = function () {
$.ajax({
url: "/Provider/CreateProvider/",
type: "POST",
data: fillModel(),
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
};


fillmodel function is

var fillModel = function () {
var providerData =
{
ProviderId: self.providerID(),
FirstName: self.firstName(),
LastName: self.lastName(),
SSN: self.SSN(),
NPI: self.NPI(),
ProviderDetails: {
ProviderDetailsId: 0,
Certification: self.certification(),
Specialization: self.specialization(),
TaxonomyCode: self.taxonomyCode(),
ContactNumber: self.contactNumber(),
ContactEmail: self.contactEmail(),
ProviderId: self.providerID()
}
}
return providerData;
}


The object data is fine on the Javascript side but at the controller,the nested objects are null as shown here.

enter image description here

Please let me know,As to what I am doing wrong.I am not able to figure this one out.

Answer

Pass the same name of columns and properties then pass into model then should be visible in you model when you pass into the controller ,

data: JSON.stringify({
     model: {
                 "Column1": $("#Column1").val(),
                 "Column2": $("#Column2").val(),
                 "Column3": $("#Column3").val(),
                 "Column4": $("#Column4").val(),
           }),

and pass the model like this because last time have find this type issue then i have fixed through this.