【发布时间】:2019-03-29 05:08:41
【问题描述】:
请让我解释一下设置。
我有一个更改密码控制器/操作和视图。 以下是我的帐户控制器中的操作签名:
public ActionResult ChangePassword(ChangePasswordMessageId? message)
[HttpPost]
public ActionResult ChangePassword(ChangePasswordViewModel model)
首次加载更改密码时,查询字符串中有一些数据。这是一个例子:
https://www.mywebsite.com/Account/ChangePassword?mobile=1
这是视图中的表单声明。
@using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
通过一个简单的提交按钮提交表单:
<div class="form-group">
<div class="col-md-offset-2 col-md-4">
<input type="submit" value="Change Password" class="btn btn-primary btn-block" />
</div>
</div>
该表单有 3 个字段:当前密码、新密码和确认密码。 如果用户正确填写了所有数据,并通过了所有客户端验证,则表单可以正常工作。除了一个用例外,一切正常。
假设用户输入的旧密码值不正确。当我到达上面的 HTTPPOST ChangePassword 操作时,它将失败。这就是代码的样子。
[HttpPost]
public ActionResult ChangePassword(ChangePasswordViewModel model)
{
if (ModelState.IsValid)
{
try
{
MembershipUser user = Membership.GetUser();
//The NEXT line is the one that fails if they supply the wrong Old Password value.
//The code then falls to the catch condition below.
bool changePassword = user.ChangePassword(model.OldPassword, model.NewPassword);
if (changePassword)
{
string path = Url.Action("ChangePassword", new { Message = ChangePasswordMessageId.ChangePasswordSuccess });
temp = Request.UrlReferrer.ToString();
pos = temp.IndexOf("?");
if (pos > 0) path += "&" + temp.Substring(pos + 1);
return RedirectToLocal(path);
}
else
{
ModelState.AddModelError("", "Change Password failed.");
}
}
catch //(Exception ex)
{
ModelState.AddModelError("", "Change Password failed.");
//ModelState.AddModelError("", ex.Message);
}
}
// If we got this far, something failed, redisplay form
//The original query string will be gone. The URLwill now only show
//https://www.mywebsite.com/Account/ChangePassword
return View(model);
}
是否可以调用“返回视图(模型);”这样原始查询字符串仍然存在吗? 我需要在页面之间维护查询字符串。除了这个用例之外,我在任何地方都可以使用它。
谢谢!
【问题讨论】:
-
在这种情况下为什么不使用 ajax 调用?
-
谢谢。我实际上是这样想的并尝试了它。但是,这并不是将 HTML.BeginForm 更改为 AJAX.BeginForm 那么简单。默认情况下,当 HTTPPost 操作返回 View(model) 时,页面什么也不做。我将不得不编写更多代码来更新显示。我正在寻找一种更通用的解决方案,可以在任何可能发生这种情况的地方应用。
标签: c# asp.net asp.net-mvc asp.net-mvc-4 post