C# model class
public class SubCategoryTwoViewModel
{
public long Id { get; set; }
public string SubCatTwoName { get; set; }
public CategoryViewModel Category { get; set; }
public SubCategoryOneViewModel SubCatOne { get; set; }
public string PictureUrl { get; set; }
public List<IFormFile> File { get; set; }
public UserViewModel AddedBy { get; set; }
public DateTime AddedOn { get; set; }
public UserViewModel Updated_By { get; set; }
public DateTime? UpdatedOn { get; set; }
public bool Active { get; set; }
}
Here is the CategoryViewModel
public class CategoryViewModel
{
public long CategoryId { get; set; }
}
Here is the controller method
[HttpPost]
public JsonResult AddEditSubCategoryTwo(SubCategoryTwoViewModel model)
{
}
Here is the ajax call which use the Form Data to serialized the data send to the controller method.
var ajaxUrl = ApplicationRootUrl("AddEditSubCategoryTwo", "Category");
var formData = new FormData();
var totalFiles = document.getElementById("subCatFile").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("subCatFile").files[i];
formData.append("File", file);
}
formData.append('SubCatTwoName', self.subCatTwoName());
var category = {
CategoryId: self.selectCategory()
};
formData.append('Category', category);
var subCatOne= {
SubCategoryOneId: self.selectCategorytwo()
};
formData.append('SubCatOne', subCatOne);
formData.append('Active', self.active());
$.ajax({
type: "POST",
contentType: false,
processData: false,
url: ajaxUrl,
data: formData,
dataType: "json",
success: function (data) {
}
});
I,am getting some field data in the controller but the java script value is not serialized to the controller model.
Here is the screenshot of the sample
In the screen shot I am getting the Category & SubCatOne field as null. But active, SubCatTwoName and File field has receive the value. I want to get Category & SubCatOne value in the controller model object. How can I achieved this.
Trying to add the object directly will not work. Instead you can make use of model binding by adding the nested fields with the correct name (separate the property hierarchy with dots). e.g.