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);
                
            }
  • 相关阅读:
    MySQL 常用到的几个字符处理函数
    MySQL DATE_SUB查询工龄大于35的员工信息
    Mysql 没有nvl()函数,却有一个类似功能的函数ifnull();
    switch 循环中的case理解
    批处理系统和分时系统各具有什么特点?为什么分时系统的响应比较快?
    存储式计算机的主要特点是什么?
    代码实现导航栏分割线
    Keras函数式API介绍
    Keras通过子类(subclass)自定义神经网络模型
    R语言kohonen包主要函数介绍
  • 原文地址:https://www.cnblogs.com/yupeiyuan/p/6297153.html
Copyright © 2011-2022 走看看