標籤

ASP.NET MVC (29) Visual C# (15) JQuery (10) Plugins (8) JQuery Plugins (6) JavaScript (6) MySQL (5) CSS (4) LinQ (4) Mac OS (4) CentOS (3) Design Pattern (3) Entity Framework (3) IIS (3) Python (3) Windows (3) php (3) Docker (2) LAMP (2) SQL Server (2) WCF (2) .NET (1) .NET Core (1) AWS (1) Browser (1) GIS (1) IE (1) Internet Security (1) Linux (1) Platform (1) React (1) SEO (1) Testing (1) VMware (1) Windows 7 (1) cookie (1) curl (1) laravel (1) phpBB (1) session (1) 中古屋 (1) 透天 (1) 閒言閒語 (1) 面試 (1) 鳥松 (1)

2011年3月30日 星期三

[ASP.NET MVC] Edit資料時View PostBack到Action應該如何驗證資料模型繫結

如果使用 ModelState.IsValid ,假如我們有排除某些欄位時就會變得很麻煩, 故可以使用TryUpdateMode() 。

例如:

public ActionResult Image(string id)
        [HttpPost]
        [ValidateInput(false)] //避免Controller檢查Script攻擊
        public ActionResult EditBoardHonor([Bind(Exclude = "ValidDate,CreateDate")]Models.BoardHonor postback)
        {
            postback.CreateDate = DateTime.Now;
            postback.ValidDate = DateTime.Now;
            using (MvcBodyApp.Models.BodyDBEntities db = new BodyDBEntities())
            {
                var result = (from s in db.BoardHonor where s.BoardHonorId == postback.BoardHonorId select s).FirstOrDefault();
                if (TryUpdateModel(result)) //檢查資料繫結是否正常
                {
                    db.SaveChanges();
                    ViewData["resultMsg"] = String.Format("【{0}】編輯成功", postback.Title);
                    return View(postback);
                }
            }
            ViewData["resultMsg"] = "編輯失敗";
            return View(postback);
        }

沒有留言:

張貼留言