ASP.NET视图视图表单验证
视图表单验证
初始化项目
新建一个ASP.NET MVC的项目
新建游戏用户类:
public class StemUsers
{
public int id { get; set; }
public string userName { get; set; }
public string pwd { get; set; }
}
创建一个BaseController
public class BaseController : Controller
{
// GET: Base
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(StemUsers stemUsers)
{
StemUsers stemUsers1 = new StemUsers();
stemUsers1.userName = Request["userName"];
stemUsers1.pwd = Request["pwd"];
List<StemUsers> list = new List<StemUsers>();
list.Add(stemUsers1);
ViewBag.add = list;
return View();
}
public ActionResult Register()
{
return View();
}
}
视图Register和Index
Register
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Register</title>
@*引入样式*@
<link rel="stylesheet" type="text/css" href="~/Content/logincss/Register.css" />
@*引入jQuery*@
<script src="~/Scripts/jquery-3.4.1.js"> </script>
</head>
<body>
<div class="kdom">
<div>
<h1>注册界面</h1>
<form action="Index" method="post" onsubmit="return tjyz()">
用户名:<input type="text" name="userName" id="userName" onblur="yzyhm()" />
<span id="namets" class="tstext">*</span><br />
密码:<input type="password" name="pwd" id="pwd" onblur="yzpwd()" />
<span id="pwdts" class="tstext"></span><br />
确认密码:<input type="password" name="pwd2" id="pwd2" onblur="yzpwd2()" />
<span id="pwdts2" class="tstext"></span><br />
<input type="submit" value="注册" />
</form>
</div>
@*js*@
<script>
// 非空验证账号
function yzyhm() {
var username = $("#userName").val();
if (username == "") {
$("#namets").html("请输入账号");
$("#namets").css("color", "red");
} else {
$("#namets").html("√");
$("#namets").css("color", "green");
}
}
function yzpwd() {
var pwd = $("#pwd").val();
if (pwd.length <3) {
$("#pwdts").html("输入的字符应该在6-18");
$("#pwdts").css("color", "red","font-size","15px");
} else {
$("#pwdts").html("√");
$("#pwdts").css("color", "green","font-size", "15px");
}
}
function yzpwd2() {
var pwd = $("#pwd").val();
var pwd2 = $("#pwd2").val();
if (pwd != pwd2) {
$("#pwdts2").html("两次输入的密码不一致");
$("#pwdts2").css("color", "red");
} else {
$("#pwdts2").html("√");
$("#pwdts2").css("color", "green","font-size","15px");
}
}
function tjyz() {
var username = $("#userName").val();
var pwd = $("#pwd").val();
if (username == "" || pwd == "") {
alert("不能有空值");
return false;
} else {
return true;
}
}
</script>
</div>
</body>
</html>
Register样式
.kdom{
width:500px;
height:400px;
border-radius:5px;
box-shadow:0 2px 8px #808080;
margin:100px auto;
}
.tstext{
font-size:10px;
}
Index
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-3.4.1.min.js" type="text/javascript"></script>
</head>
<body>
<div>
<h1>主页</h1>
@foreach (var item in ViewBag.add)
{
<p>账号:@item.userName</p>
<p>密码:@item.pwd</p>
}
</div>
</body>
</html>
效果:
总结:
敲打代码的时候一定要语法正确和书写
敲打代码的时候一定要语法正确和书写
敲打代码的时候一定要语法正确和书写