MVC Action未在控制器中触发
我在视图中创建了一个模型,一些字段和一个按钮:
视图:
@model IEnumerable @foreach (var item in Model) { @Html.TextBoxFor(modelItem => modelItem.name) }
控制器:
public ActionResult Index() { var model = selectModels(); return View(model); } [HttpPost] public ActionResult Save(IEnumerable model) { return View(); }
问题是:
为什么不解雇“保存”动作?
您需要一个
元素来回发您的控件。 在您的情况下,您需要指定操作名称,因为它与生成视图的方法( Index()
)不同
@using (Html.BeginForm("Save")) { .... // your controls and submit button }
现在这将回发到Save()
方法,但是模型将为null,因为foreach
循环生成重复的name
属性而没有索引器意味着它们不能绑定到集合(由于重复的id
属性,它也会创建无效的html) )。
您需要使用for
循环(模型必须实现IList
)或自定义EditorTemplate
类型的Employee
。
使用for循环
@model IList @using (Html.BeginForm("Save")) { for (int i = 0; i < Model.Count; i++) { @Html.TextBoxFor(m => m[i].name) } }
使用EditorTemplate
在/Views/Shared/EditorTemplates/Employee.cshtml
@model EnrollSys.Employee @Html.TextBoxFor(m => m.name)
并在主视图中
@model IEnumerable // can be IEnumerable @using (Html.BeginForm("Save")) { @Html.EditorFor(m => m) }