首页 > 解决方案 > 如何在表单中创建对象数组,然后将此数组发送到控制器?

问题描述

如何Step在表单中创建多个对象,当我单击“创建”按钮时,这些对象会发送到控制器的 POST 方法?

我不知道我用什么来显示我根据@Html助手创建的 Step 对象数组,我想,然后最终在“创建”时发送到控制器。

此外,我需要考虑编辑和删除步骤,如下图所示。

为配方添加步骤的表单图像

配方模型

    public class Recipe
    {
        public int RecipeId { get; set; }

        [RequiredIfButtonClicked("CreateRecipe")]
        [StringLength(50, ErrorMessage = "Title cannot be longer than 50 characters.")]
        [Display(Name = "Title:")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$", ErrorMessage = "Must start with a capital letter, only alphabetic characters and no spaces allowed.")]
        public string Name { get; set; }

        // Used to create a single Step for a Recipe
        public Step Step { get; set; }

        // A Recipe has many steps
        public Step[] Steps { get; set; }
    }

阶梯模型

    public class Step
    {
        public int StepId { get; set; }

        [RequiredIfButtonClicked("CreateRecipe", ErrorMessage = "At least one step is required.")]
        [StringLength(500, ErrorMessage = "Instructions cannot be longer than 500 characters.")]
        [Display(Name = "Step Instructions:")]
        public string Instruction { get; set; }

    }

标签: c#asp.net.netasp.net-mvc

解决方案


在您的情况下,我建议使用 jQuery 使用FormData向控制器发送 Ajax 请求。

我想您已经为Add Step按钮定义了一些事件来使用 JavaScript 收集数据。

数据看起来像:

var steps = ['step_1', 'step_2'];

在您的模型中,因为Step类需要Instruction属性,您可以使用该数组创建一个循环来创建一个新模型:

var model = {};
model.Steps = [];

for (var step of steps) {
  model.Steps.push({ Instruction: step });
}

您还可以使用此模型添加更多属性,例如NameStep对象:

model.Name = $('.Title').val();
model.Step = {
  Instruction: steps[0]
};

然后,将数据压缩到FormData发送前:

var data = new FormData();
data.append('Name', model.Name);
data.append('Step', model.Step);
data.append('Steps', model.Steps);

$.ajax({
  url: '/your_controller',
  type: 'your_request_type',
  data: data
}).done(function (response) {
  console.log('Responsed data from server:', response);
}).fail(function (error) {
  // If there is some error: path not found or invalid request format...
  // the error can be logged here
  console.error(error);
});

推荐阅读