检查,模型值MVC3中没有任何更改

时间:2014-03-06 10:32:00

标签: asp.net-mvc-3 object post model

我的模型如下:

public class Page
{
     private readonly IndianTime _g = new IndianTime();

     public Page()
     {
         CreatedOn = _g.DateTime;
         Properties = "Published";
         Tags = "Page";
         RelativeUrl = string.Empty;
     }

     public string Path
     {
         get { return (ParentPage != null) ? ParentPage.Heading + " >> " + Heading : Heading; }
     }

     [Key]
     public int Id { get; set; }

     [StringLength(200), Required, DataType(DataType.Text)]
     public string Title { get; set; }

     [StringLength(200), Required, DataType(DataType.Text)]
     public string Heading { get; set; }

     [MaxLength, Required, DataType(DataType.Html)]
     public string Content { get; set; }

     [Display(Name = "Reference Code"), ScaffoldColumn(false)]
     public string ReferenceCode { get; set; }

     [Required]
     [Remote("CheckDuplicate", "Page", ErrorMessage = "Url has already taken", AdditionalFields = "initialUrl")]
     public string Url { get; set; }

     [Display(Name = "Created On"), ScaffoldColumn(false)]
     public DateTime CreatedOn { get; set; }

     //Parent Page Object (Self Reference: ParentId = > Id)
     [Display(Name = "Parent Page")]
     public int? ParentId { get; set; }

     [DisplayFormat(NullDisplayText = "Root")]
     public virtual Page ParentPage { get; set; }

     public virtual ICollection<Page> ChildPages { get; set; }
}

在更新期间,有没有检查POST方法后模型值是“已更改”还是“没有更改”?

比如说:(见注释行)

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(WebPage webpage)
{
   try
   {
      if (ModelState.IsValid)
      {
          // If (webpage object values are unchanged, submitted as it is
          // {
          //    Do not insert any values into Another Table
          // }
          // else
          // {
          //    Inert into another table
          // }
          _db.Entry(webpage).State = EntityState.Modified;
          _db.SaveChanges();
          return RedirectToAction("Index");
      }
   }
   catch (DataException)
   {
        ModelState.AddModelError("", ErrorCode.Msg.ContactSystemAdmin.ToString());
   }
   return View(webpage);
}

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(WebPage webpage)
{
   try
   {
      if (ModelState.IsValid)
      {
          var dbEntry=_db.GetEntryById(webpage.Id);
           //check here if properties in webPage and column values in dbEntry are 
           //same then decide whether to insert in another table or not

          _db.Entry(webpage).State = EntityState.Modified;
          _db.SaveChanges();
          return RedirectToAction("Index");
      }
   }
   catch (DataException)
   {
        ModelState.AddModelError("", ErrorCode.Msg.ContactSystemAdmin.ToString());
   }
   return View(webpage);
}

或者当然不确定

尝试在客户端使用$(form).serialize()

CHECK THIS FIDDLE