【发布时间】:2015-08-26 21:41:55
【问题描述】:
我想编辑一个项目列表并将它们全部保存在同一个提交中。是否可以?如果有,怎么做?
我有以下代码,但它没有给出想要的结果。否则我不知道为控制器中的对应写什么。
@using (Html.BeginForm("Save", "MyController", FormMethod.Post))
{
<fieldset>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Datum</th>
<th>NewValue</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.HiddenFor(modelItem => item.Id)
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value)
</td>
<td>
@Html.TextBoxFor(modelItem => item.Value)
</td>
</tr>
}
</tbody>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
更新感谢@Jonesopolis,我想出了这个可行的解决方案
@using (Html.BeginForm("Save", "MyController", FormMethod.Post))
{
<fieldset>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Datum</th>
<th>NewValue</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
@Html.HiddenFor(modelItem => modelItem[i].Id)
@Html.DisplayFor(modelItem => modelItem[i].Name)
</td>
<td>
@Html.DisplayFor(modelItem => modelItem[i].Value)
</td>
<td>
@Html.TextBoxFor(modelItem => modelItem[i].Value)
</td>
</tr>
}
</tbody>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
对于我的控制器
public class MyController : Controller
{
[HttpPost]
public ActionResult Save(IEnumerable<NameDoesNotMatter> newValues)
{
...
}
}
public class NameDoesNotMatter
{
public int Id { get; set; }
public decimal? Value { get; set; }
}
现在看看我是否可以使用模板解决问题。 @StephenMuecke的链接应该足够了
更新 2 好吧,现在的代码并不难
@using (Html.BeginForm("Save", "MyController", FormMethod.Post))
{
<fieldset>
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
<th>Datum</th>
<th>NewValue</th>
</tr>
</thead>
<tbody>
@Html.EditorForModel()
</tbody>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
对于 Views/Shared/EditorTemplates/TypeOfModel.cshtml
@model TypeOfModel
<tr>
<td>
@Html.HiddenFor(item => item.Id)
@Html.DisplayFor(item => item.Name)
</td>
<td>
@Html.DisplayFor(item => item.Value)
</td>
<td>
@Html.TextBoxFor(item => item.Value)
</td>
</tr>
控制器保持不变
【问题讨论】:
-
是的,这很有可能。在这里使用
for循环而不是foreach循环。您的提交应将集合返回给控制器。 -
请参阅 this answer 了解为什么需要
for循环或EditorTemplate -
我想我可以使用这些答案......会尝试。
-
我想接受你的一个答案,但无法接受评论
-
没问题(反正我已经把它标记为重复)——当你获得必要的代表时,你总是可以投票给其他答案
标签: c# asp.net-mvc asp.net-mvc-4 razor html.beginform