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
}
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).
You need to use a for
loop (the model must implement IList
) or a custom EditorTemplate
for type of Employee
.
Using a for loop
@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%" />
}
Using an EditorTemplate
In /Views/Shared/EditorTemplates/Employee.cshtml
@model EnrollSys.Employee
@Html.TextBoxFor(m => m.name)
and in the main view
@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%" />
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…