MVC中ajax提交表单示例
页面中:
@using (Ajax.BeginForm("Login", "User", new AjaxOptions() { HttpMethod = "post", OnSuccess = "afterOk" })) { <input ...一些表单 <input type="checkbox" id="ckbrecord" name="ckbrecord" checked="checked" value="true"> 记住我,下次免登录哦! <input type="submit" value="提交" /> }
js:
<script> function afterOk(data) { var arr = data.split(":"); if (arr[0] == "ok") { if (arr[1] == "文印管理员") window.location.href = "/Admin/Print"; else if (arr[1] == "insert") window.location.href = "/User/EditUserInfo"; else window.location.href = "/Admin/Report"; } else $("#showMsg").text(arr[1]).closest(".row").removeClass("hidden"); } </script>
controller
public ActionResult Login(User user) { if (string.IsNullOrEmpty(user.Name) || string.IsNullOrEmpty(user.Pwd)) { return Content("no:请输入完整,不能为空!"); } user.Loginip = Request.UserHostAddress.ToString(); user.Registertime = DateTime.Now; dao.UpdateUserToCurrentBase(user);//只更新数字校园中得到的数据到当前库中 User dbuser = dao.GetUserByName(user); var record = Request["ckbrecord"].ToBoolean(); SetCookie(record, user); Session["userinfo"] = dbuser; return Content("ok:" + dbuser.Rank); }
当然我更喜欢直接使用jquery的ajax提交表单
$.ajax({ cache: true, type: "POST", url:ajaxCallUrl, data:$('#yourformid').serialize(),// 你的formid async: false, error: function(request) { alert("Connection error"); }, success: function(data) { $("#commonLayout_appcreshi").parent().html(data); } });