我有这个模型,其中包含另一个模型的列表。然后在我看来,我的表单填写了我的主要模型的几个字段。但我希望这个表单也能够添加其他类型的 X 模型并全部连接起来,我想知道如何正确地做到这一点。
所以这是我的两个模型:
public class MyMainModel
{
public int MyMainId { get; set; }
[Required(ErrorMessage = "Groovy name required")]
[Display(Name = "MyMainModel's groovy name:")]
public string Name { get; set; }
public List<MySubModel> MySubModels { get; set; }
}
public class MySubModel
{
public int MySubId { get; set; }
[Required(ErrorMessage = "Cool name required")]
[Display(Name = "MySubModel's cool name:")]
public string Name { get; set; }
}
当我为我的“创建”视图点击我的控制器时,我会执行以下操作:
public ActionResult SomePageAboutCreating()
{
// [...] Some other stuff
return View(new MyMainModel());
}
现在这发送到我的强类型视图:
@model myFunProject.WebModels.MyMainModel
<div>
<form id="my-create-form" onsubmit="CreateMyMainModel(this); return false;">
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="result" style="background-color: silver;">This is the operation result box</div>
<img class="loading" src="/Images/ajax-loader.gif" alt="Loading..." width="16" height="16" style="display: none;" />
<section>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
</section>
<!-- Here begins the fields for my list of "MySubModel" -->
@Html.EditorFor(x => x.MySubModels)
<!-- Here I'm thinking about a javascript that will add the previous fields X times so that the user can create "MyMainModel" as well as x times "MySubModel"... -->
<input type="submit" class="btn-send" id="my-create-form-submit" value="Send" />
</form>
</div>
所以我想我必须在这里使用 EditorTemplates ......所以我在我的 /Views/EditorTemplates/MySubModels.cshtml 中设置(根据我的“MyMainModel”的属性命名),然后当我在那里写我的表格时,我使困惑...
@model myFunProject.WebModels.MyMainModel
@*<section>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
</section>*@
所以在这里我不确定在这里放什么......我希望我的 Name 属性是“MySubModel”之一。当用户看到这个表单时,比如说他将经历这个场景:
- 输入“MyMainModel”的名称。
- 转到另一个名称框并填写“MySubModel.
- 然后他会单击一个特殊按钮,该按钮将操纵 dom 以附加另一个 MySubModel.Name 字段。
- 他会写第二个“MySubModel”名字。
- 他会点击提交。
我放在那里的ajax调用我可以进行接线,但是我的困惑来自我必须为编辑器模板编写的代码,然后我有点想知道我将如何创建一个新的字段(例如,对于第二个“MySubModel”......)。
任何帮助将不胜感激,我已经阅读了许多有关与此相关的主题的文章,但尚未找到此案例。谢谢!
编辑:
我将添加提交表单时由我的 ajax 调用的操作(一个过于简化的版本呵呵)。
public ActionResult CreateMyMainModel(MyMainModel myMainModel) {
// [...] Do stuff like save to database...
// var aGroovyNAme = myMainModel.Name;
foreach(var mySubModel in myMainModel.MySubModels) {
// Here I would have the sub models available to manipulate...
// var aCoolName = mySubModel.Name;
}
return Content("ok");
}