Evg*_*kiy 0 .net c# asp.net-mvc-3
让我们有成像模型:
public class InheritModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string OtherData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我们有一个带View的控制器,代表这个模型:
private InheritModel GetAll()
{
return new InheritModel
{
Name = "name1",
Description = "decs 1",
OtherData = "other"
};
}
public ActionResult Index()
{
return View(GetAll());
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以在View中编辑它,更改一些数据并发回到服务器:
[HttpPost]
public ActionResult Index(InheritModel model)
{
var merged = new MergeModel();
return View(merged.Merge(model, GetAll()));
}
Run Code Online (Sandbox Code Playgroud)
我需要做什么:
有人可以帮我制作这种Merge方法吗?
UPDATE(!)
这不是一项微不足道的任务.接近如:
public InheritModel Merge(InheritModel current, InheritModel orig)
{
var result = new InheritModel();
if (current.Id != orig.Id)
{
result.Id = current.Id;
}
}
Run Code Online (Sandbox Code Playgroud)
不适用.它应该是通用解决方案.我们在模型中有200多个属性.第一个模型是从DB的严格表格构建的.
public InheritModel Merge(InheritModel current, InheritModel orig)
{
var result = new InheritModel();
if (current.Id != orig.Id)
{
result.Id = current.Id;
}
if (current.Name != orig.Name)
{
result.Name = current.Name;
}
... for the other properties
return result;
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是使用反射并遍历所有属性并设置它们的值:
public InheritModel Merge(InheritModel current, InheritModel orig)
{
var result = new InheritModel();
var properties = TypeDescriptor.GetProperties(typeof(InheritModel));
foreach (PropertyDescriptor property in properties)
{
var currentValue = property.GetValue(current);
if (currentValue != property.GetValue(orig))
{
property.SetValue(result, currentValue);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
显然,这仅适用于1级属性嵌套.
| 归档时间: |
|
| 查看次数: |
4159 次 |
| 最近记录: |