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);
                }
            });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM