zoukankan      html  css  js  c++  java
  • ASP.NET MVC 4 创建、编辑Model时的数据绑定

      [Bind(Exclude = "LeagueID")]的作用是设置利用Action提交Model给View时,不会把“LeagueID”属性的值绑定到Model中。

      一般自增的列不必绑定。

      在Action的参数中设置时,只会在该Action的作用范围内起作用;而在Model实体类文件中设置时,则会在之后所有Action中起作用。

      例如:试图在View中Create一个新的Model实体时,如果“LeagueID”在数据库中是自增字段,那么Model.IsValid为false。此时在Action方法的入参中设置[Bind(Exclude = "LeagueID")]则可以不在Model中绑定“LeagueID”,可以正常完成Model的验证;

    [HttpPost]
            public ActionResult Create([Bind(Exclude = "LeagueID")]League league)//这里数据绑定时排除LeagueID,因为是自增字段,所以Create不需要给它赋值
            {
                try
                {
                    // TODO: Add insert logic here
                    league.Enable = 1;
                    if (ModelState.IsValid)
                    {
                        db.Leagues.Add(league);
                        db.SaveChanges();
                        return RedirectToAction("Index");
                    }
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }

      而在View中Edit某个实体的属性时,如果在Action入参中设置“LeagueID”排除绑定,则用Entity Framework调用SaveChanges()保存修改结果时会报如下错误:

      “Store update, insert, or delete statement affected an unexpected number of rows (0). ”

      出现该报错的原因时,在db.Entry(league).State = EntityState.Modified的前提下,因为“LeagueID”被排除在绑定之外,默认为0,对于数据库来说是一个新添加的数据,所以会出现以上报错。

    [HttpPost]
            public ActionResult Edit(League league)
            {
                    // TODO: Add update logic here
                    if (ModelState.IsValid)
                    {
                        db.Entry(league).State = EntityState.Modified;
                        db.SaveChanges();
                        return RedirectToAction("Index");
                    }
                    ViewBag.SubjectionID = new SelectList(db.Subjections, "SubjectionID", "SubjectionName", league.SubjectionID);
                    return View(league);
                
            }
  • 相关阅读:
    MySQL5.6 GTID、多线程复制
    WPS for Linux(ubuntu)字体配置(字体缺失解决办法)
    linux下用phpize给PHP动态添加扩展
    Zabbix汉化方法
    [FTP] Pure-FTPd SSL/TLS 配置方法
    PHP 缓存扩展opcache
    sftp搭建
    nginx https使用
    iptables基本规则
    kvm虚拟机安装
  • 原文地址:https://www.cnblogs.com/yupeiyuan/p/6297153.html
Copyright © 2011-2022 走看看