Ajax调用MVC控制器参数为实体

前端之家收集整理的这篇文章主要介绍了Ajax调用MVC控制器参数为实体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

mvc有一个很好的特性,可以把JQ使用Ajax请求的时候,把json解析成为后台的实体类。这里举一个简单的例子。

前台完整代码

@{
Layout = null;
}


<!DOCTYPE html>


<html>
<head>
<Meta name="viewport" content="width=device-width" />
<title>添加系统用户</title>
<script src="~/Plugins/Easyui/jquery.min.js"></script>
<script type="text/javascript">
function btnAdd_click() {
var UserPassWord = $('#txtUserPassWord').val();
var UserPassWord2 = $('#txtUserPassWord2').val();
if (UserPassWord != UserPassWord2) {
alert('两次填写的密码必须相同。');
return;
}
var userdata = {
'UserAccount': $('#txtUserAccount').val(),
'UserPassWord': $('#txtUserPassWord').val(),
'UserName': $('#txtUserName').val(),
}
$.ajax({
type: "post",
url: "/UserManage/AddUser",
data: userdata,
dataType: "json",
success: function (msg) {
alert(msg);
}
});
}
</script>
</head>
<body>
<div>
<table>
<tr>
<td>登录账号:</td>
<td>
<input type="text" id="txtUserAccount" /></td>
</tr>
<tr>
<td>登录密码:</td>
<td>
<input type="text" id="txtUserPassWord" /></td>
</tr>
<tr>
<td>确认登录密码:</td>
<td>
<input type="text" id="txtUserPassWord2" /></td>
</tr>
<tr>
<td>用户名:</td>
<td>
<input type="text" id="txtUserName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="button" id="btnAdd" onclick="btnAdd_click();" value="添加" /></td>
</tr>
</table>
</div>
</body>
</html>

控制器写法:

/// <summary>
/// 添加系统用户
/// </summary>
/// <param name="user">系统用户信息</param>
/// <returns>执行结果</returns>
public JsonResult AddUser(Entity.SUser user)
{
return Json(BLL.UserManage.AddUser(user),JsonRequestBehavior.AllowGet);
}

实体类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entity { /// <summary> /// 系统用户表 /// </summary> public class SUser { private int? id; /// <summary> /// 自增ID /// </summary> public int? ID { get { return id; } set { id = value; } } private string userAccount; /// <summary> /// 用户账号 /// </summary> public string UserAccount { get { return userAccount; } set { userAccount = value; } } private string userPassWord; /// <summary> /// 用户密码 /// </summary> public string UserPassWord { get { return userPassWord; } set { userPassWord = value; } } private string userName; /// <summary> /// 用户姓名 /// </summary> public string UserName { get { return userName; } set { userName = value; } } } }

猜你在找的Ajax相关文章