表单数据未在asp.net核心mvc控制器模型中序列化 [英] Form Data not serialized in asp.net core mvc controller model

查看:71
本文介绍了表单数据未在asp.net核心mvc控制器模型中序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is the CategoryViewModel

public class CategoryViewModel
    {
        public long CategoryId { get; set; }
}

这是控制器方法

[HttpPost]
public JsonResult AddEditSubCategoryTwo(SubCategoryTwoViewModel model)
{
}

这是ajax调用,它使用表单数据序列化发送到控制器方法的数据。

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) {
    }
});

我在控制器中获取一些字段数据,但java脚本值未序列化到控制器模型。

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

在屏幕截图中我得到了类别& SubCatOne字段为空。但活动,SubCatTwoName和File字段已收到值。我想得到分类&控制器模型对象中的SubCatOne值。我怎样才能实现这一点。

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.

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

这篇关于表单数据未在asp.net核心mvc控制器模型中序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆