如何在表单中创建对象数组,然后将该数组发送到控制器?

问题描述

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

我不知道我该如何使用@Html帮助器显示我创建的Step对象数组,然后最终将它们发送到“创建”上的控制器。

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

谢谢

Image of the form to add Steps for a recipe

食谱模型

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

    }

解决方法

对于您而言,我建议使用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);
});