From: http://www.cnblogs.com/henq/archive/2009/08/31/1557726.html
It is often necessary to process forms in projects and assign values to models, which is annoying and repetitive. Code . Code of the following side: Code
News news = New News ();
News. ID = Int . Parse (request. Form [ " ID " ]);
News. Category = Int . Parse (request. Form [ " Category " ]);
News. Title = Request. Form [ " Title " ];
News. createtime = Datetime. parse (request. Form [ " Createtime " ]);
Errors often occur, especially when you work overtime to write this boring code...
Reflection, generics, and static methods can easily solve this problem. It seems a little advanced, but it is actually super simple. See the code. Code
Public Static Class Henqpost < T > Where T: New ()
{
/**/ /// <Summary>
/// Assign a value to Model
/// </Summary>
/// <Typeparam name = "T"> Model </Typeparam>
/// <Param name = "T"> Model </Param>
/// <Param name = "form"> Request </Param>
/// <Returns> </returns>
Public Static Int Getpost < T > ( Ref T, namevaluecollection form)
{
Int VA = 0 ;
Type type = T. GetType (); // Retrieve type
Propertyinfo [] pi = Type. getproperties (); // Get Attribute Set
Foreach (Propertyinfo P In Pi)
{
If (Form [P. Name] ! = Null )
{
Try
{
P. setvalue (T, convert. changetype (Form [P. name], p. propertytype ), Null ); // Assign a value to an attribute and convert the key value type to the attribute type.
VA ++ ; // Number of successfully Assigned attributes
}
Catch
{
}
}
}
Return Va;
}
}
the main reason why static methods are used is that graphs are convenient and new is not needed.
in the future, all the forms can be easily processed, and the two lines of code can be done.
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> News news = New News ();
henqpost News > . getpost ( ref News, request. form);
// the annoying way to assign values to object classes is over.
NO configuration is required. Conventions are the best configuration.
Convention: The name of a form item is best matched with the attribute name of the object class (if you want to change it, the reflection method is modified according to your own rules ).
assign a value to a form. If it is a webform, you can use this method. You can write it down by yourself. The principle is similar.