zoukankan      html  css  js  c++  java
  • 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#
  • 相关阅读:
    [公告]博客园新服务器已下订单
    清除SearchNet.exe
    [新闻]微软将在2007年发布的Office产品阵容
    卸载Internet Explorer 7 Beta 2 Preview引起原来的IE无法正常使用
    博客园准备购买新服务器
    [微软活动公告]微软最有价值专家(MVP)四月份在线申请开始了
    [公告]今晚数据库迁移至新服务器
    请wz不要把别人的文章当作自己的文章发表
    SQL Server 2000 To SQL Server 2005
    [公告]博客园数据库已成功迁移至新服务器
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/4134783.html
Copyright © 2011-2022 走看看