Ajax 按需 提交指定字段 以 Json Model 形式 post 到 action

Action 如下,其中传递过来的master已经从json model 转换为 实体Model
        [HttpPost]
        
public ActionResult Edit(Master master)
        {           
            
if (ModelState.IsValid)
            {
               
 db.Master.Attach(master);//附加到DBContext
                SetModifiedPropertyByNeed<Master>(master);//把前天传递过来的JsonModel字段都标记为更新
                db.SaveChanges();
                
return RedirectToAction("Index");
            }
            
return View(master);
        }

利用反射,查找Model中 传递过来的指定字段,并将其 stateEntry 设置为 已更新。


public void SetModifiedPropertyByNeed<T>(T t)
        {
            
if (t == null)
            {
                
return;
            }

            System.Reflection.PropertyInfo[] properties 
= t.GetType().GetProperties();

            
if (properties.Length <= 0)
            {
                
return;
            }
            
foreach (System.Reflection.PropertyInfo item in properties)
            {
                
string name = item.Name; //名称
                object value = item.GetValue(t, null);  //

                
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    
if (value != null)
                    {
//值不为null的都是需要更新的字段。
                        var stateEntry = ((IObjectContextAdapter)db).ObjectContext
                                        .ObjectStateManager.GetObjectStateEntry(t);
                        stateEntry.SetModifiedProperty(name);
                    }
                }
                
else
                {
                    SetModifiedPropertyByNeed(value);
                }
            }

        }

  参考文献:

   1 、dudu的 新问题新方法:在Entity Framework中实现指定字段更新 

posted @ 2011-06-03 14:37  大大宝  阅读(774)  评论(0编辑  收藏  举报