[英]How can I validate in a modal bootstrap from server side?
I have an Account
Controller and when an incorrect username/password is entered in a bootstrap modal, I want it to return a message "Invalid login attempt." 我有一个
Account
控制器,当在引导程序模式中输入错误的用户名/密码时,我希望它返回一条消息“无效的登录尝试”。 from ActionResult Login()
to the modal. 从
ActionResult Login()
到模态。
My _loginPartialView: 我的_loginPartialView:
<div id="loginModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<section id="loginForm">
@using (Ajax.BeginForm("Login", "Account", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "loginModal" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
<div style="text-align:right;">
<button type="submit" class="btn btn-primary btn-sm">Submmit</button>
</div>
}
</section>
</div>
</div>
</div>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('.launchLoginModal').click(function () {
$('#loginModal').modal({
keyboard: false
});
});
});
</script>
My Account
Controller: 我的
Account
管理员:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return PartialView("_LoginModalPartial", model);
}
}
I added a comment about this, but it may help as your solution. 我添加了关于此的评论,但它可能有助于您的解决方案。 It sounds like invalid inputs on form submission leads to a redirect with the modal content on a blank page?
听起来表单提交上的无效输入导致在空白页面上重定向模态内容? Since the modal is a partial view, try moving your scripts to the top of the _loginPartialView.
由于模态是局部视图,因此请尝试将脚本移动到_loginPartialView的顶部。 The same may hold true for any bundles you are using in the layout page.
对于您在布局页面中使用的任何捆绑包,情况也是如此。
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div id="loginModal" class="modal fade">
...
</div>
First, since you're using @Ajax helpers, you should install and reference Microsoft jQuery Unobtrusive Ajax (you can find an older but still pertinent guide here: https://www.asp.net/mvc/overview/older-versions/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript ). 首先,既然你正在使用@Ajax助手,你应该安装并引用Microsoft jQuery Unobtrusive Ajax(你可以在这里找到一个较旧但仍然相关的指南: https : //www.asp.net/mvc/overview/older-versions/创建一个mvc-3-application-with-razor-and-unobtrusive-javascript )。
Second, you should enable client side validation (see in the guide) 其次,您应该启用客户端验证(请参阅指南)
Third, you need to specify as UpdateTargetId an existing DOM element to be updated (I do not see the "loginModal" in the code sample). 第三,您需要将UpdateTargetId指定为要更新的现有DOM元素(我在代码示例中没有看到“loginModal”)。 I believe that this id should be inside the modal html code, otherwise it will recreate the modal html and reset its status.
我相信这个id应该在modal html代码中,否则它将重新创建模态html并重置其状态。 (I would move the modal definition in the parent view and let the partial with only the form definition).
(我会在父视图中移动模态定义,并让部分仅包含表单定义)。
Generally: 通常:
ModelState.AddModelError("", "Invalid login attempt.");
ModelState.AddModelError("", "Invalid login attempt.");
(You obviously, can use any choice of words like 'success' or whatever.) (显然,你可以使用任何选择,比如“成功”等等。)
Your razor could look something like: 你的剃刀可能看起来像:
// on login button click
$('#btnSubmit').on('click', function() {
$("#loginForm").validate(); // using jqueryvalidate
if ($('#loginForm').valid()){ // if valid, submit
// Get values from Modal and put into JSON object mimicking correct model
var token = $('input[name="__RequestVerificationToken"]').val(); // this is required for the anti-forgery decoration and must be structured outside the model to be submitted
var model = {
Email: $('#Email').val(),
Password: $('#Password').val()
};
var ajaxData = {
__RequestVerificationToken: token,
model: model
}
// send
$.ajax({
type: "GET",
url: '@Url.Action("method", "controller")',
data: ajaxData,
success: function (msg) {
// ajax success, but see if the login was a success
if (msg.IsError == 'true'{ all good}
else {
if (msg.Message != 'success'){
$('#UserFeedback').val('Invalid Login')
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.info(errorThrown);
// userfeedback
$('#UserFeedback').html(errorThrown);
});
}
});
}
});
Your controller could return a custom viewmodel like: 您的控制器可以返回自定义视图模型,如:
public class LoginCheckViewModel
{
[DisplayName("IsError")]
public string IsError {get; set;}
[DisplayName("Message")]
public string Message { get; set; }
}
You controller would check the login as you have, but then return 你的控制器会像你一样检查登录,但然后返回
myLoginCheckViewModel = new LoginCheckViewModel();
myLoginCheckViewModel.IsError = [true/false];
myLoginCheckViewModel.Message = [success/fail];
return Json(myLoginCheckViewModel, JsonRequestBehavior.AllowGet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.