0
我有一個視圖,它通過ajax調用局部視圖。局部視圖有一個包含在另一個Ajax表格中的表格。每行包含兩個提交按鈕,我希望將其映射到兩個不同的操作,即保存和刪除。但是,當我提交任一按鈕時,沒有數據傳遞給控制器。 String submitAction
和ProjectComment projectcomment
不包含表單中的數據評論數據。我有以下代碼:如何在Razor MVC中使用多個提交按鈕5.2.3 Ajax
MyView的:
Index.cshtml
@model MyProject.Areas.MyComments.Models.ProjectComment
@using (Ajax.BeginForm("Details", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "commentTbl" // place content within #commentTbl
}, new { @class = "form-inline" }))
{
@Html.AntiForgeryToken()
<p>...</p>
<div class="ibox float-e-margins">...</div>
}
<div id="commentTbl">...Partial View is loaded here...</div>
管窺
Details.cshtml
@model IEnumerable<MyProject.Areas.MyComments.Models.ProjectComment>
@using (Ajax.BeginForm("Update", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "commentTbl" // place content within #commentTbl
}, new { @class = "form-inline" }))
{
<div class="ibox float-e-margins">
<div class="ibox-title">...</div>
<div class="ibox-content">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover dataTables-example" id="dataTables-comments">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Comment)
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@{int i = 0;}
@foreach (var projectcomment in Model)
{
<tr>
<td>
@Html.EditorFor(modelItem => projectcomment.Comment)
</td>
<td>
<button type="submit" id="save" class="btn btn-primary" name="Save" value='@i'>Save</button>
<button type="submit" id="delete" class="btn btn-primary" name="Delete" value='@i'>Delete</button>
</td>
</tr>
i++;
}
</tbody>
</table>
</div>
</div>
</div>
}
我的控制器
CommentController.cs
[HttpPost]
public ActionResult Update(ProjectComment projectcomment, String submitAction)
{
// submitAction is null and projectcomment contains no form data.
if (submitAction.Equals("Save"))
return RedirectToAction("Save", projectcomment);
else if (submitAction.Equals("Delete"))
return RedirectToAction("Delete", projectcomment);
else
return HttpNotFound();
}
[HttpPost]
public ActionResult Save([Bind(Include="Comment")] ProjectComment projectcomment)
{
// ... to do logic here
}
請幫助我做錯了什麼。
謝謝,提交Action正確傳遞,但「ProjectComment projectcomment」仍爲空。我甚至嘗試在'Update'中添加'[Bind(Include =「Comment」)]',它仍然是空的。 – usr4896260
您是否將projectcomment傳遞給Save方法或Update方法時遇到問題?您是否能夠成功將您的項目評論發佈到您的更新方法? – m0g
其實我弄明白了。在我的'@ foreach'循環中,我將'var item'重命名爲'var projectcomment',它完美地工作。謝謝! – usr4896260