模态对话框无重定向
模态对话框无重定向
我使用的是C# MVC 5版本。我有一个使用部分视图的模态对话框中的表单。我想要提交表单而不进行重定向,只是希望对话框关闭。这可以实现吗?
以下是我的代码:
@title
@using (Html.BeginForm("Edit", "Region", FormMethod.Post, new { onsubmit = "return validateForm();", @class = "form-horizontal" })) { }
public ActionResult Edit(int id) { RegionViewModels regionViewModels = MakeRegionViewModels(id); return PartialView("_InsertTaxRegion", regionViewModels); }
Modal Dialog No Redirect的问题出现的原因是在使用jQuery时,当使用<input type="submit" />
提交表单时,页面会发生重定向,导致无法在后台发送表单数据并关闭模态框。
解决方法是使用jQuery的$.post()
方法将表单数据序列化并以后台发送数据的方式提交表单,然后关闭模态框。如果使用<input type="submit" />
提交表单,则需要使用以下代码阻止表单提交:
$('form').submit(function(e){ e.preventDefault(); });
通过以上方法,可以解决Modal Dialog No Redirect的问题。
问题原因:使用Bootstrap模态框时,点击关闭按钮或提交按钮后,页面会自动重定向到指定的URL,造成页面跳转。
解决方法:在模态框的关闭按钮和提交按钮上添加"data-dismiss"属性,并设置为"modal",这样点击按钮后就不会自动重定向。
修改后的代码如下:
@model NCR.Models.Employee @{ ViewBag.Title = "Edit"; }Edit
@using (Html.BeginForm()) { @Html.AntiForgeryToken()}@Html.LabelFor(model => model.FIRST_NAME, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.FIRST_NAME, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FIRST_NAME, "", new { @class = "text-danger" })@Html.LabelFor(model => model.LAST_NAME, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.LAST_NAME, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.LAST_NAME, "", new { @class = "text-danger" })
这样修改后,点击关闭按钮或提交按钮后,页面不会跳转。