我是带有 Razor 的 .Net MVC 4 的新手,我完全有可能以错误的方式处理这个问题,但这是我的问题:我正在尝试构建一个在网格中显示记录的站点,每个记录都允许编辑,最后有一个提交所有按钮。在每条记录中,用户可以添加评论并单击保存按钮(在他们正在编辑的行上),该按钮将使用相应行的 FormCollection 回发到控制器。问题是最后提交所有按钮。用户应该能够对多行进行编辑并单击提交所有按钮以保存对所有记录的更改,而无需单独单击每行的保存按钮。
我一直在尝试使用 Form of Forms 方法,通过将整个表格封装在一个表格中,该表格将回发到一个操作方法,该方法将循环通过 FormCollection 参数中的 FormCollections 来为每个调用 Save 函数已经变了。似乎 Razor 不喜欢整个 Form of Forms 的想法。有没有更好的方法来添加这个功能?
这是我的观点:
@using COM.COMPANY.APPS.MODELS
@model COM.COMPANY.APPS.WEBAPP.ViewModels.MyModel
@{
ViewBag.Title = "Web Application Title";
}
@using(Html.BeginForm("Submit", "Home"))
{
<h1>@ViewBag.Message</h1>
@Html.CheckBox("CheckAll", false) //Flags All Projects For Approval
<div>
<table id="projGrid">
<tr>
<th>Check to Approve</th>
<th>Comment</th>
<th>Save</th>
</tr>
@foreach (var item in Model.List)
{
<tr>
@using(Html.BeginForm("Save", "Home"))
{
<td class='narrowCell'>
@Html.CheckBoxFor(x => item.isApproved)
</td>
<td class='textInputCell'>@Html.TextAreaFor(x => item.NewComment, 6, 40, new { title = "New Comments...", @class = "defaultText" })</td>
<td class='narrowCell'><input type="submit" value="Save" /></td>
}
</tr>
}
</table>
</div>
<br />
<input type="submit" value="Submit" />
}
这是我的控制器保存功能:
[HttpPost]
public ActionResult Save(FormCollection form)
{
bool isAppr = Convert.ToBoolean(form["item.isApproved"].ToString().Contains("true"));
string newComment = form["item.NewComment"];
try
{
DataItem item = new DataItem
{
isApproved = isAppr,
NewComment = newComment
};
DataGateway.SaveDataItem(item);
return Index();
}
catch
{
Console.WriteLine("FAILED TO SAVE RECORD");
return Index();
}
}
public ActionResult Submit(FormCollection form)
{
//Need to collect form of forms here
return Index();
}
我确信有更好的方法来做到这一点。我正在考虑只在整个表格上使用一个大表单,并让各个保存按钮使用 javascript 函数来传递记录 id 参数 - 这样,如果设置了参数,则保存函数只保存来自 FormCollection 的记录字段,如果没有,那么它会运行并保存所有内容。