我的登录验证有问题。我的JQuery
没有触发这就是为什么Json
数据没有通过。我希望它在进入控制器之前首先触发JQuery
。它转到控制器,但问题是没有触发.submit
()函数,这就是没有传递ajax数据的原因。谢谢。
LogIn.cshtml
@model DTS.Models.User
<h2>LogIn</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.UserID)
<div class="form-group">
@Html.LabelFor(model => model.Username, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Username, new {@id = "Username" })
@Html.ValidationMessageFor(model => model.Username)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { @id = "Password" })
@Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log In" class="btn btn-default" id="Login"/>
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<script>
$("#Login").submit(function () {
var dataObject = { UsernName: $("#Username").val(), Password: $("#Password").val() };
$.ajax({
url: Url.Action("LogIn", "User"),
type: "POST",
data: dataObject,
datatype: "json",
success: function(result)
{
if (result.toString()=="Success!") {
alert(result);
}
else
{
alert(result);
}
},
error: function(result)
{
alert("Error");
}
});
})
</script>
UserController.cs
[HttpPost]
public ActionResult LogIn(User user)
{
string message = "";
DynamicParameters param = new DynamicParameters();
param.Add("@Username", user.Username);
param.Add("@UserID", user.Password);
if (ModelState.IsValid)
{
if (DapperORM.ExecuteReturnScalar<User>("LogInUser", param) == null)
{
message = "Success!";
}
else
{
message = "Username or Password is incorrect!";
}
}
else
{
message = "Required fields.";
}
if (Request.IsAjaxRequest())
{
return Json(message, JsonRequestBehavior.AllowGet);
}
else
{
return RedirectToAction("Index", "Document");
}
}
试试下面的代码。它会工作。
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
// rest code goes here
});
});
在这里,我做了两处修改。
submit
事件。e.preventDefault()
。这将阻止提交按钮单击执行整页回发。