MVC中model binding的坑

这两天发现一个model binding中的坑,就是action中的参数名不能和属性重复,否则绑定不了,参数始终是null,

举例说明: 

T_Account类定义如下

    public partial class T_Account
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(50)]
        public string Account { get; set; }

        [StringLength(50)]
        public string Name { get; set; }

        public bool IsDeleted { get; set; }
    }

在Edit视图提交时的处理方法定义

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Account,IsDeleted,Name")] T_Account account)
        {
            if (ModelState.IsValid)
            {
                db.Entry(account).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(account);
        }

注意此时Include中有Account属性,参数名也叫account, account始终为null.

 

但如果把参数account改个名字,例如t_account,问题就解决了

        public ActionResult Edit([Bind(Include = "Id,Account,IsDeleted,Name")] T_Account t_account)
        {

 

posted @ 2016-07-30 11:56  羽扇冠巾  阅读(444)  评论(1编辑  收藏  举报