C#模型类
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; }
}
这是 CategoryViewModel
public class CategoryViewModel
{
public long CategoryId { get; set; }
}
这是 Controller 方法
[HttpPost]
public JsonResult AddEditSubCategoryTwo(SubCategoryTwoViewModel model)
{
}
这是使用表单数据序列化发送到 Controller 方法的数据的 ajax 调用。
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) {
}
});
我正在 Controller 中获取一些字段数据,但 java 脚本值未序列化到 Controller 模型。
在屏幕截图中,我将 Category & SubCatOne 字段设置为 null。但是active、SubCatTwoName 和File 字段已收到值。我想在 Controller 模型对象中获取 Category & SubCatOne 值。我怎样才能做到这一点。
最佳答案
尝试直接添加对象是行不通的。相反,您可以通过添加具有正确名称的嵌套字段来使用模型绑定(bind)(用点分隔属性层次结构)。例如
formData.append('Category.CategoryId', self.selectCategory());
关于javascript - 表单数据未在 asp.net core mvc Controller 模型中序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43533820/