请让我解释一下设置。
我有一个更改密码 Controller /操作和 View 。 以下是我的帐户 Controller 中的操作签名:
public ActionResult ChangePassword(ChangePasswordMessageId? message)
[HttpPost]
public ActionResult ChangePassword(ChangePasswordViewModel model)
首次加载更改密码时,我在查询字符串中有一些数据。这是一个例子:
https://www.mywebsite.com/Account/ChangePassword?mobile=1
这是 View 中的表单声明。
@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 个字段:当前密码、新密码和确认密码。 如果用户正确填写了所有数据,并通过了所有客户端验证,则表单可以正常工作。除一个用异常(exception),一切正常。
假设用户输入了一个不正确的旧密码值。当我执行上面的 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);
}
是否可以调用“return View(model);”这样原始查询字符串仍然存在? 我需要逐页维护查询字符串。除了这个用例,我在任何地方都可以使用它。
谢谢!
最佳答案
如果有人仍在寻找此解决方案,请尝试不提供 Controller 和操作名称。
@using (Html.BeginForm(null, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
关于c# - MVC Post 导致 QueryString 在重新加载同一 View 时丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24804007/