您的位置:首页 > 编程语言 > C#

C# MVC结合AJAX实现登录窗口(新手看)

2018-03-07 21:10 459 查看
using System.Web.Mvc;
using System.Windows.Forms;
using MvcMySchool.Models;
using static MvcMySchool.Models.Common;
using System.Web.Routing;

namespace MvcMySchool.Controllers
{
public class UsersController : Controller
{
// GET: Users
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null,"Default",new RouteValueDictionary(new { }));
return View();
}
[HttpPost]//响应来自前台的请求
public ActionResult Login(string userName,string userPassWord)//参数个数、名字,要求和前台传来的一样
{
string messge = "登陆成功!";
int code = 1;
User user = null;
LoginStatus status=UserManager.Login(userName, userPassWord, out user);
if (status == LoginStatus.UserNameNoExisit)//LoginStatus枚举直
{
messge = "用户名不存在!";
code = 0;
}
else if (status == LoginStatus.PassworeError)
{
messge = "密码不正确!";
code = 0;
}
JsonResult ajaxres = new JsonResult();
ajaxres.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
ajaxres.Data = new { messge = messge, code = code };
return ajaxres;
}

}
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>登录窗口</title>
</head>
<body style="background-color:aquamarine">
<form>
<input id="UserName" class="text-input" type="text"  />
<input id="UserPassWord" class="text-center"  />
<input id="button" class="submit" type="button"   />
</form>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$("#button").click(function () {
var userName = $("#UserName").val();
var userPassWord = $("#UserPassWord").val();
if(userName=="" || userPassWord=="")
{
alert("用户名或密码不能为空!");
return;
}
$.ajax({
type: 'POST',
data: {
userName: userName,
userPassWord: userPassWord
},
dataType: 'json',
url: '@Url.Action("Login")',
success: function (data) {
if (data.code != 1) {
alert(data.messge);
}
else {
window.location.href='@Url.Action("Index","Home")'
}
}
})
})
</script>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AJAX简单应用 C#
相关文章推荐