62,025
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test02.Models
{
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Test02.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
return View();
}
}
}
@model Test02.Models.User
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form>
<input type="text" id="userID" />
<input type="text" id="password" />
<input type="submit" value="登录"/>
</form>
</div>
</body>
</html>
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
public ActionResult LoginAction()
{
object data;
string userName = Request.Form["UserName"];
string userPwd = Request.Form["UserPwd"];
if(userName == "admin" && userPwd == "123")
data = new { type = "1", message = "用户名密码正确,登录成功!" };
else
data = new { type = "0", message = "用户名密码正确,登录失败!" };
return Json(data, JsonRequestBehavior.AllowGet);
}
}
View里面引用Jquery,通过Ajax将数据传到Controller里面
<html>
<head>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnLogin").click(function () {
$.ajax({
url: "/Login/LoginAction",
type: "Post",
data: $("#LoginForm").serialize(),
dataType: "json",
success: function (data) {
if (data == 1) {
alert(data.message);
}
else {
alert(data.message);
}
}
});
});
});
</script>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form id="LoginForm">
UserName : <input type="text" id="userID" name="UserName" /> <br/>
UserPwd: <input type="text" id="password" name="UserPwd"/> <br />
<input type="button" id="btnLogin" value="登录" />
</form>
</div>
</body>
</html>
如果你需要和数据库打交道了,再去搞Model的内容 <form action="/User/Login" method="post">
<input type="text" id="Name" name="Name" />
<input type="text" id="password" name="password" />
<input type="submit" value="登录" />
</form>
action对应后台controller的方法,input元素中的name名称跟后台model定义的属性名称要一致。
controller中的login(action)可以这么写:
[HttpPost]
public ActionResult Login(User user)
{
//这里的user对象就是view提交过来的,可以获取输入的参数,读取数据库进行比较
return View();
}
httppost特性就指定为只允许post动作。