我是asp MVC的新手,所以我会尝试使用ajax创建一个登录表单,所以我写了jsonresult来检查控制器中的用户名和密码,我在ajax中调用它但是它不工作并且我不知道为什么这样我的控制器代码
public ActionResult login()
{
return View();
}
[HttpPost]
public JsonResult ValidateUser(string username,string password)
{
using(var contxt=new EnglisCenterEntities())
{
var data = from a in contxt.Employee
where a.Username == username && a.Passwords == password
select a;
if(data.Count()>0)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
}
这是我的观点和ajax代码
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 alert alert-warning">
<h2 class="text-center">Login</h2>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<button class="btn btn-warning form-control" type="submit" id="savedata"><i class="glyphicon glyphicon-log-in"></i> Login</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#savedata').click(function () {
var data = {
"username": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/ValidateUser",
type: "Post",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("@Url.Action("Index", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "@Url.Action("Login", "Account")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
</script>
为什么它不起作用?任何帮助,请
答案 0 :(得分:3)
不需要JSON.stringify
,修改您的ajax电话data
,如下所示: -
$.ajax({
url: "/Account/ValidateUser",
type: "Post",
data: data,
dataType: "json",
.....
});