利用Ajax调用controller方法并传递参数,控制器用自定义的类接收数据
前端提交代码
$.ajax({ type: "POST", url: "/Login/DoAction", datatype: "json",
data: '{ "AccountName": "' + accountname + '", "Password": "' + pwd + '" }', contentType: "application/json; charset=utf-8", success: function (data) { //data是返回的JSON数据 if (data.Result == "true") { $('#message').text("登陆成功,跳转中..."); window.location.href = "/HOME/Index"; //打开页面 } else { $('#message').text(data.Msg); } }, error: function (e) { alert(e.responseText); }, beforeSend: function () { $('#login').attr("disabled", true); $('#message').text("正在登陆处理,请稍候..."); }, complete: function () { $('#login').attr("disabled", false); } });
控制器方法:
[HttpPost]
public JsonResult DoAction(LoginUserInfo loginUserInfo) { //登录验证 bool result = SysUserRepository.CheckUserAndPassword(loginUserInfo); object message = string.Empty; if (result) { //Controller.Session 属性 , Session[LoginUserInfo.Session_Name] = loginUserInfo; message = new ResposeInfo { Msg = "执行成功", MsgCode = "0000", Result = "true" }; } else message = new ResposeInfo { Msg = "账号或密码错误!", MsgCode = "1000", Result = "false" }; return Json(message, JsonRequestBehavior.DenyGet); }
public class LoginUserInfo { /// <summary> /// 超级用户角色名称 /// </summary> public const string _SuperUserRoleName = "管理员"; /// <summary> /// 保存的Session名称 /// </summary> public const string Session_Name = "LoginUserInfo"; public string AccountName { get; set; } public string Password { get; set; } public int DepartID { get; set; } public string RoleName { get; set; } }
控制器收到json数据,根据名称匹配,LoginUserInfo其它成员没有值,即部分赋值。