您的位置:首页 > Web前端 > JavaScript

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

2011-06-03 14:37 351 查看
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中实现指定字段更新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: