问题描述
我在视图中创建了一个模型、一些字段和一个按钮:
I made a model, some fields and a button in the view:
查看:
@model IEnumerable<EnrollSys.Employee>
@foreach (var item in Model)
{
@Html.TextBoxFor(modelItem => modelItem.name)
}
<input type="submit" value="Save" class="btn btn-default" style="width: 20%" />
控制器:
public ActionResult Index()
{
var model = selectModels();
return View(model);
}
[HttpPost]
public ActionResult Save(IEnumerable<EnrollSys.Employee> model)
{
return View();
}
问题是:
为什么不触发保存"操作?
Why the "Save" action isn't fired?
推荐答案
您需要一个 元素来回发您的控件.在您的情况下,您需要指定操作名称,因为它与生成视图的方法不同 (
Index()
)
You need a <form>
element to post back your controls. In your case you need to specify the action name because its not the same as the method thet generated the view (Index()
)
@using (Html.BeginForm("Save"))
{
.... // your controls and submit button
}
这现在将回发到您的 Save()
方法,但是模型将为空,因为您的 foreach
循环正在生成重复的 name
没有索引器的属性意味着它们不能绑定到集合(由于重复的 id
属性,它也会创建无效的 html).
This will now post back to your Save()
method, however the model will be null because your foreach
loop is generating duplicate name
attributes without indexers meaning that they cannot be bound to a collection (its also creating invalid html because of the duplicate id
attributes).
您需要为 Employeefor
循环(模型必须实现 IList
)或自定义 EditorTemplate
/代码>.
You need to use a for
loop (the model must implement IList
) or a custom EditorTemplate
for type of Employee
.
使用 for 循环
@model IList<EnrollSys.Employee>
@using (Html.BeginForm("Save"))
{
for (int i = 0; i < Model.Count; i++)
{
@Html.TextBoxFor(m => m[i].name)
}
<input type="submit" value="Save" class="btn btn-default" style="width: 20%" />
}
使用 EditorTemplate
在/Views/Shared/EditorTemplates/Employee.cshtml
@model EnrollSys.Employee
@Html.TextBoxFor(m => m.name)
在主视图中
@model IEnumerable<EnrollSys.Employee> // can be IEnumerable
@using (Html.BeginForm("Save"))
{
@Html.EditorFor(m => m)
<input type="submit" value="Save" class="btn btn-default" style="width: 20%" />
}
这篇关于MVC 动作未在控制器中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!