在Asp.net mvc 5.我们有一个登录页面,它实现HTML.BeginForm()将数据发布到控制器,如果用户名和密码不正确,我们使用部分视图将错误发送回前端。一切正常,如果出现错误,屏幕上只显示错误消息,而不是其他内容。
控制器
[HttpPost]
public ActionResult SingleSSOMPLogin(SSoStateModel model)
{
//Check the Code with SP providers and Authorization server.
if(model.SAMLAssertion.validMPData)
{
return RedirectToAction("SSOServiceMP" , "SAML");
}else
{
//Error message processed.
model.errorMessage = SSOState.SAMLAssertion.errorMessage;
return PartialView("_LoginError" , model);
}
}
该视图包含以下代码
<div class="peripheral">
<div class="panel panel-default panel-peripheral">
@{Html.Partial("_LoginError", Model);}
<div class="panel-heading clearfix">Please Log In</div>
<div class="panel-body">
<div class="brand-logo eop-logo">
<script type="text/javascript">
function changeImage() {
document.getElementById("Logo").src = '@Url.Content("~/Content/images/TopLogo.gif")';
}
</script>
<img id="Logo" width="200" src='@Url.Content("~/Content/images/TopLogo.gif")' onerror="changeImage()" />
@{ Html.EnableClientValidation(true);}
<!--Ajax call to Controller-->
@using (Html.BeginForm("SingleSSOMPLogin", "Accounts"))
{
@Html.ValidationSummary(true);
<div id="group-email" class="form-group col-md-12 ">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control", placeholder = "Please enter your Email address" })
@Html.ValidationMessageFor(m => m.Email)
</div>
<div id="group-password" class="form-group col-md-12">
@Html.PasswordFor(m => m.Password, new { @class = "form-control", placeholder = "Please enter your password" })
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary pull-left">Login</button>
<a id="forgot" href='@Url.Action("ForgotPassword","Accounts")' class="btn btn-link btn-sm pull-right">Forgot your password?</a>
</div>
</div>
}
</div>
</div>
</div>
</div>
部分视图
@{
Layout = null;
}
@if (Model.Result!= null)
{
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>@Model.Result.errorMessage</strong>
</div>
}
当出现错误时,我再次重定向到同一视图,所有查询参数都消失了,只显示错误信息。
如何解决以下问题?
答案 0 :(得分:1)
部分视图将仅返回您定义的片段。 因此,当使用
从“完整”视图调用时@{Html.Partial("_LoginError", Model);}
它将生成视图的相应部分。
在您的情况下,最常见的是添加模型错误并返回完整视图(必须具有ValidationSummary部分):
[HttpPost]
public ActionResult SingleSSOMPLogin(SSoStateModel model)
{
//Check the Code with SP providers and Authorization server.
if(model.SAMLAssertion.validMPData)
{
return RedirectToAction("SSOServiceMP" , "SAML");
}else
{
//Error message processed.
ModelState.AddModelError("error", SSOState.SAMLAssertion.errorMessage);
return View(model);
}
}
如果要使用局部视图,则必须从javacript ajax调用中调用它,并在页面中插入响应。使用jQuery,它或多或少像:
$.ajax({ url: <partial view url>,
type: 'GET',
success: function (result) {
$(updateSelector).hide().html(result).effect("fade", "fast");
}
});