ASP.NET MVC中用反射自动保存提交的表单

先前用TryUpdateModel,发现貌似不能保存例如某个字段为DateTime.Now对象的,或者有主从表的时候不知道怎么保存对应的从表id对象.如果有知道的朋友麻烦PM我.谢谢..

因此,写了这个方法,用于自动保存提交的表单,单独处理的就用另外一个参数进行处理,性能方面暂时不考虑.反射是个好东西.

 

 

代码
public string  AutoSave(object InObj,object otherAttributes)
        {
            
string err = string.Empty;
            Type objType 
= InObj.GetType();
            PropertyInfo[] objPro 
= objType.GetProperties(BindingFlags.Public|BindingFlags.Instance);
            
foreach (PropertyInfo property in objPro)
            {

                
if (otherAttributes.ToString().IndexOf(property.Name) == -1)
                {
                    
if (Request[property.Name] != null)
                    {
                        
try
                        {
                            objType.GetProperty(property.Name).SetValue(InObj, Convert.ChangeType(Request[property.Name], property.PropertyType), 
null);
                        }
                        
catch (Exception ex)
                        {
                            err 
+= property.Name + " | " + ex.Message + "<br />";
              
                        }
                    }
                }
                
else
                {
                    
foreach (var Attribute in new RouteValueDictionary(otherAttributes))
                    {
                        
if (property.Name == Attribute.Key)
                        {
                            
try
                            {
                                objType.GetProperty(property.Name).SetValue(InObj, Attribute.Value, 
null);
                            }
                            
catch (Exception ex)
                            {
                                err 
+= property.Name + " | " + ex.Message + "<br />";
                        
                            }

                        }
                    }
                }
                
            }



            
return err;
        }

 

 

调用的时候,这样用:

 

string err = AutoSave(en, new { news_time = DateTime.Now, news_kind = _db.news_kind.First(m => m.nk_id == XXX) });

 

 

这样,需要特殊处理的字段就额外处理.剩下的一般的int的,string的都可以自动保存.

posted @ 2009-12-03 12:14  gxpotato  阅读(793)  评论(0)    收藏  举报