ASP.Net MVC 前台表单序列化,后台C#解析处理
任务如下图所示,该网页用于创建一个用户信息
前台代码
注意:应用ajax提交表单时,提交按钮应为button,不要使用submit,否则无法回调success函数,submit提交表单时刷新了一下页面,无法找回回调函数路径
<html>
<head>
<script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
</head>
<body>
<h2>This is a Create Page</h2>
<h4>UserInfo</h4>
<br />
<form class="form-horizontal" id="form-create">
<div class="form-group col-md-10">
<label>UserName</label>
<input id="name" name="Name" type="text" placeholder="请输入用户名" class="form-control" />
</div>
<div class="form-group col-md-10">
<label>Password</label>
<input id="password" name="Password" type="text" placeholder="请输入用户密码" class="form-control" />
</div>
<div class="form-group col-md-10">
<input id="submit" type="button" value="Create" class="btn btn-default" />
</div>
</form>
<div>
<a href="/UserInfo/Index">Back to List</a>
</div>
<script type="text/javascript">
$("#submit").click(function () {
$.ajax({
url: "/UserInfo/CreateSubmit",
type: "POST",
data: { serializeData: $("#form-create").serialize() },//表单序列化
dataType: "json",
success: function (data) {
if (data == true) {
window.location.href = "/UserInfo/Index";
}
}
})
});
</script>
</body>
</html>
后台代码
public ActionResult Create()
{
return View();
}
public JsonResult CreateSubmit(string serializeData)
{
string[] arrayForm = serializeData.Split('=', '&');
Dictionary<string, object> dicForm = new Dictionary<string, object>();
//解析序列化信息 转换成字典
for (int i = 0; i < arrayForm.Length - 1; i = i + 2)
{
string value = System.Web.HttpUtility.UrlDecode(arrayForm[i + 1]);
dicForm.Add(arrayForm[i], value);
}
//获取字典值,应用EF存入数据库
UserInfo userInfo = new UserInfo();
userInfo.Name = dicForm["Name"].ToString();
userInfo.Password = dicForm["Password"].ToString();
db.UserInfo.Add(userInfo);
db.SaveChanges();
//回调success
return Json(true,JsonRequestBehavior.AllowGet);
}