当操作中有参数时,模型绑定会隐式工作。也可以使用控制器中的UpdateModel和TryUpdateModel来进行显示绑定。

  若绑定期间有错或者模型无效,那么UpdateModel方法会抛出一个异常。

  

        public ActionResult Edit([Bind(Include = "ID,Name")] Product product)
        {
            if (ModelState.IsValid)
            {
                UpdateModel<Product>(product);
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(product);
        }

 

  TryUpdateModel方法可以调用模型绑定,但是不会抛出异常。TryUpdateModel会返回一个bool值,true:模型绑定成功,模型是有效的;false:模型过程中出现错误

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name")] Product product)
        {
            if (ModelState.IsValid)
            {
                if (TryUpdateModel<Product>(product))
                {
                    db.Entry(product).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }

            return View(product);
        }