【发布时间】:2016-01-17 21:05:18
【问题描述】:
我有一个问题,我正在加载部分页面,但是我不希望当我单击保存按钮时此页面上的表单重定向。
不确定我是否以正确的方式使用脚本,我想在单击提交时发布到控制器,但我想重定向回我所在的同一页面 (AdminPanel/AdminProfile),而不是重定向到不同的控制器/视图 (Account/Manage)。
管理员资料视图:
<div id="tab-2" class="tab-pane">
@{Html.RenderPartial("~/Views/Account/Manage.cshtml");
}
</div>
不确定我的脚本应该进入此视图还是保留在部分视图中?
控制器:
public ActionResult Manage(LocalPasswordModel model)
{
//....
return Json(new { redirectTo = Url.Action("AdminProfile", "AdminPanel") });
}
带有脚本的部分视图:
@model LocalPasswordModel
@{
ViewBag.Title = "Change Password";
}
<section class="hgroup">
<div class="panel-body">
<ul class="breadcrumb pull-right top-right">
<li>You're logged in as <strong>@User.Identity.Name</strong></li>
</ul>
<ul class="message-success">@ViewBag.StatusMessage</ul>
@using (Html.BeginForm("Manage", "Account", FormMethod.Post, new { id = "SavePassword", @class = "form-horizontal" }))
{
<div class="social_sign">
<h3>Change your password.</h3>
</div>
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group">
<label class="col-sm-2 control-label">Old Password</label>
<div class="col-sm-10">
@Html.PasswordFor(m => m.OldPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
@Html.PasswordFor(m => m.NewPassword, new { @class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col">
<input type="submit" class="btn btn-primary pull-right" value="Change password" />
</div>
</div>
}
</div>
</section>
上面视图中的脚本:
@section Scripts {
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
})
</script>
@Scripts.Render("~/bundles/jqueryval")
}
似乎什么都没有发生,我得到的只是一个带有{"redirectTo":"/AdminPanel/AdminProfile"} 的空白页面。哪个是网址:http://localhost:57239/Account/Manage
【问题讨论】:
-
在
if语句中的事件处理程序中使用event.preventDefault();或return false; -
你在 if 语句中提到下面的答案说它在 if 之外?
-
如果表单无效,验证插件默认会阻止表单提交,只有当表单有效并且要使用 ajaxPOST 数据时才需要停止页面重定向>
-
是否使提交按钮只是一个常规按钮,并且处理点击事件而不是提交事件是不可能的?
标签: javascript jquery json ajax asp.net-mvc