MVC的TryUpdateModel

MVC的TryUpdateModel

我们在使用MVC的时候,给model赋值只需要 TryUpdateModel(model) 就搞定了,而在webForm,winForm中,我们要写长长的 xx.xx = Convert.Toint( xxx.text) ...如果一个model有30个属性,就要写30行,看着都累!

这里有一篇 webForm 的文章:http://www.cnblogs.com/coolcode/archive/2009/08/15/1546936.html 借用了一下~

那winForm能否也借用呢?

我尝试写了一个扩展类(只实现了int,string,datetime类型,其它的可以扩展)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class Expand : Form
{
    public void TryUpdateModel<TModel>(ref TModel model)
    {
        Type mod = model.GetType();
        PropertyInfo[] property = mod.GetProperties();
        object obj = Activator.CreateInstance(mod);
        foreach (PropertyInfo pi in property)
        {
            if (Controls.ContainsKey(pi.Name))
            {
                if (pi.PropertyType == typeof(DateTime))
                {
                    try
                    {
                        pi.SetValue(obj, ((DateTimePicker)Controls[pi.Name]).Value, null);
                    }
                    catch { }
                }
                else if (pi.PropertyType == typeof(int))
                {
                    try
                    {
                        pi.SetValue(obj, int.Parse(Controls[pi.Name].Text), null);
                    }
                    catch { }
                }
                else
                {
                    try
                    {
                        pi.SetValue(obj, Controls[pi.Name].Text, null);
                    }
                    catch { }
                }
            }
        }
        model = (TModel)obj;
    }
}

  然后,我们就可以

1
2
3
var model = new Class1();
 
this.TryUpdateModel<Class1>(ref model);

  不过,看着ref那么碍眼呢?

不知道各位大神 ~ 有没有更好点的办法

 https://devlib.codeplex.com/SourceControl/latest#main/product/Codes/DevLib.ExtensionMethods/ObjectExtensions.cs

public static void CopyPropertiesFrom(this object source, object target)
分类: C#
原文地址:https://www.cnblogs.com/Leo_wl/p/4134783.html