Form Data not serialized in asp.net core mvc controller model

送分小仙女□ 提交于 2020-01-04 05:57:12

问题


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.


回答1:


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.

formData.append('Category.CategoryId', self.selectCategory());


来源:https://stackoverflow.com/questions/43533820/form-data-not-serialized-in-asp-net-core-mvc-controller-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!