c# - 如何在表单中创建对象数组,然后将此数组发送到控制器?
问题描述
如何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; }
}
解决方案
在您的情况下,我建议使用 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 });
}
您还可以使用此模型添加更多属性,例如Name
或Step
对象:
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);
});
推荐阅读
- javascript - 关闭包含我在 Selenium 中的“加载更多”按钮的随机视频弹出广告
- scala - 使用 spark-scala 获取字符编码信息
- powerpoint - 如何在PowerPoint中为非常长的图像制作动画(像信用场景一样从下到上滚动)
- mysql - 如何确保以一定的时间间隔更新到数据库
- opencascade - 如何在 OpenCASCADE 上创建浮雕和雕刻文字
- react-native - 反应本机中的 TurboModuleRegistry.getEnforcing(...) 错误
- python - 用已经存在的 id 列替换编码器列表
- html - 无法从 rvest 中的 html_node 提取 href 链接
- vue.js - 使用 v-if 显示隐藏 div 导致按钮不触发
- material-ui - Lighthouse Aria-Label 错误——如何纠正?