我有用于测试目的的简单页面。因此,我有一个“索引”页面,该页面具有一个用于选择国家/地区的下拉列表和一个用于进行搜索的按钮,该按钮将一些信息显示为表中的行列表。
@using (Ajax.BeginForm("GetList", "test", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "showResult"
}))
在我的控制器中,它返回局部视图。
[HttpPost]
public ActionResult GetList(int CountryId)
{
var model = db.Names
.Include(x => x.Country)
.Where(x => x.Country.CountryId == CountryId).ToList();
return PartialView("PartialPosting", model);
}
在我的PartialPosting视图中,有一个按钮可以调用可以提交笔记的模式对话框。
@model IEnumerable<test.Models.Names>
<table class="table table-hover">
<tr>
<th>Note</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.ActionLink("Button", "button", "test", null, new { @class = "btn btn-danger btn-xs", data_toggle = "modal", data_target = "#modal-container" })
</td>
</tr>
}
</table>
<div id="modal-container" class="modal fade" tableindex="-1" role="dialog">
<div class="modal-content">
<div class="modal-body">
</div>
</div>
</div>
单击按钮后,它将转到控制器中的按钮方法,该方法返回将以模式显示的视图
<div class="modal-body">
按键方式:
public ActionResult Button()
{
return View();
}
按钮视图:
@model test.ViewModels.NoteViewModel
@using (Html.BeginForm("PostNote", "test", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.TextAreaFor(model => model.Note)
<input type="submit" value="Submit" />
}
和PostNote方法:
[HttpPost]
public ActionResult PostNote(NoteViewModel model)
{
//codes
--> ?? return RedirectToAction();
}
一切正常,但这是我的问题。当模态提交注释时,
由于这涉及到ajax响应,因此我不确定如何将正确的URL返回到先前的状态。
您必须使表单提交在按钮视图(便笺表单)中成为ajax表单提交,并在处理来自该表单的表单发布数据的PostNote操作方法中,返回json响应。在ajax表单提交的成功回调中,只需隐藏/关闭模式对话框,您将在第一页看到原始按钮和下拉菜单。
因此,更新您的按钮视图(Button.cshtml
),以提供一个表单Id
,稍后我们将使用该表单来连接ajaxified表单提交事件。
@{
Layout = null;
}
@model test.ViewModels.NoteViewModel
@using (Html.BeginForm("PostNote", "test", FormMethod.Post,new {id="postNoteForm"}))
{
@Html.AntiForgeryToken()
@Html.TextAreaFor(model => model.Note)
<input type="submit" value="Submit" />
}
<script>
$(function() {
$(document).on("submit", "#postNoteForm", function(e) {
e.preventDefault();
$.post($(this).attr("action"),$(this).serialize(),function(response) {
console.log('response from ajax call', response);
if (response.status === "success") {
$('#modal-container').modal('hide');
} else {
alert(response.errorMessage);
}
})
});
})
</script>
假设您的PostNote
httppost操作方法返回带有status
&errorMessage
属性的json响应(如果发生错误)
[HttpPost]
public ActionResult PostNote(NoteViewModel model)
{
try
{
// to do : Save data
return Json(new {status="success"});
}
catch(Exception ex)
{
return Json(new {status="error", errorMessage = ex.Message });
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句