zoukankan      html  css  js  c++  java
  • UpdateModel 和TryUpdateModel用法总结

      当操作中有参数时,模型绑定会隐式工作。也可以使用控制器中的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);
            }    
    

      

  • 相关阅读:
    php 数组处理
    PHP 递归几种方法
    PHP取一算法
    oracle的db link
    sql2008破解加密存储过程
    ATT 解锁手机
    jQuery 通配符
    win10 Enable developer Mode
    Win8.1 远程桌面 凭据无法工作
    html5media.js 让浏览器兼容<Video><Audio> 标签
  • 原文地址:https://www.cnblogs.com/kittyguo/p/4635884.html
Copyright © 2011-2022 走看看