我有一个使用bootstrap Modal作为登录部分视图的项目,但是我希望有一个异步解决方案来验证用户登录,所以通过jquery.post
将数据传递给行动,但我找到了{ {1}}成功完成但行动没有回应。
查看:
jquery.post
使用Javascript:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Login </h4>
</div>
<div class="container">
<div class="modal-body" id="signinForm">
@using (Ajax.BeginForm("Login", "Account", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "signinForm" }, new { @id = "targetForm" }))
{
// Html.BeginForm("Login", "Account", FormMethod.Post, new { @id = "signinForm" });
@Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<div id="errorresult"></div>
<div class="control-group">
<label class="control-label" for="inputEmail">User Name</label>
<div class="controls">
@Html.TextBoxFor(m => m.UserName, new { @name = "inputUser", @class = "form-control", @id = "inputUser", @placeholder = "User Name" })
@Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
@Html.TextBoxFor(m => m.Password, new { @name = "inputPassword", @class = "form-control", @id = "inputPassword", @placeholder = "Password", @type = "password" })
@Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
Remember me @Html.CheckBoxFor(m => m.RememberMe, new {@id="rememberMe"})
<span class="span9">@Html.ActionLink("Register", "Register", "Account") </span>
</label>
<button type="submit" id="submit_btn" class="btn btn-primary">sign in</button>
</div>
</div>
}
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
我的行动:
$('#submit_btn').click(function (event) {
event.preventDefault();
var targetForm = $('#targetForm').serialize();
var newtargetForm= targetForm.replace(/&/g, "?");
$.post("@Url.Action("AjaxLogin", "Account")?"+ newtargetForm, {
userName: $('#targetForm #inputUser').val(),
passWord: $('#targetForm #inputPassword').val(),
rememberMe:$('#targetForm #rememberMe').is(':checked')
}, function (data, textStatus, xhr) {
/*optional stuff to do after success */
console.log(textStatus);
})
})
根据我的理解,asp.net mvc的路由规则应该有效,但事实并非如此。
答案 0 :(得分:0)
问题:
type="submit"
会导致Web浏览器通过回发提交表单(因为您的method
属性设置为“POST”),这会导致页面刷新。发生这种情况时,页面上的所有javascript都会终止,因为您实际上是在转到另一个页面或重新加载当前页面。
从Ajax call doesn't work when a submit button is used
被盗 解决方案:
更改
<button type="submit" id="submit_btn">
至<button type="button" id="submit_btn">
并保留其余的代码。