如何在ASP.NET MVC中使用多个表单元素
所以我是ASP.NET MVC的新手,我想为一个集合中的每个项目创建一个带有文本框的视图。 我该怎么做,以及如何在POST回来时捕获信息? 我使用表单和表单元素为模型构建静态表单,但从不基于可变大小的集合动态生成表单元素。
我想在mvc 3中做这样的事情:
@foreach (Guest guest in Model.Guests) { First Name:
@Html.TextBoxFor(???) @* I can't do x => x.FirstName here because the model is of custom type Invite, and the lambda wants to expose properties for that type, and not the Guest in the foreach loop. *@ }
如何为每位客人提供文本框? 我如何在它回发的动作方法中捕获它们?
谢谢你的帮助。
绝对是编辑器模板的工作。 所以在你看来,你把这一行:
@Html.EditorFor(x => x.Guests)
并在相应的编辑器模板内( ~/Views/Shared/EditorTemplates/Guest.cshtml
)
@model AppName.Models.Guest First Name:
@Html.TextBoxFor(x => x.FirstName)
这就是全部。
现在,以下操作将开箱即用:
public ActionResult Index(int id) { SomeViewModel model = ... return View(model); } [HttpPost] public ActionResult Index(SomeViewModel model) { if (!ModelState.IsValid) { return View(model); } // TODO: do something with the model your got from the view return RedirectToAction("Success"); }
请注意,编辑器模板的名称很重要。 如果视图模型中的属性是:
public IEnumerable Guests { get; set; }
编辑器模板应该称为Guest.cshtml
。 它将自动为Guests
集合的每个元素调用,它将负责正确生成输入的id和名称,以便在POST回来时一切都自动运行。
结论:每次在ASP.NET MVC视图中编写循环( for
或foreach
)时,您应该知道自己做错了,并且有更好的方法。
你可以这样做:
@for (int i = 0; i < Model.Guests.Count; i++) { @Html.TextBoxFor(m => m.Guests.ToList()[i].FirstName) }
Haacked在这篇文章中有更多的例子和细节。
更新:控制器发布操作应如下所示:
[HttpPost] public ActionResult Index(Room room) { return View(); }
在这个例子中,我认为你有一个像这样的Room类:
public class Room { public List Guests { get; set; } }
这就是全部,在post post上,你应该正确填充Guests列表。
上述就是C#学习教程:如何在ASP.NET MVC中使用多个表单元素分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1007965.html