See this article: Using Reflection, generic, static methods to quickly obtain the form value to the Model.
I sorted it out.
Code
Using System;
Using System. Data;
Using System. Configuration;
Using System. Linq;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. HtmlControls;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Xml. Linq;
Using System. Reflection;
Using System. Collections. Specialized;
Public class ModelHeper
{
/// <Summary>
/// Confirm the control naming rules
/// </Summary>
/// <Typeparam name = "T"> model type </typeparam>
/// <Param name = "model"> model object </param>
/// <Param name = "e"> current page Request. Form </param>
/// <Returns> Number of successfully assigned values </returns>
Public static T modelBind <T> (NameValueCollection fromTest) where T: new ()
{
T model = new T ();
Object NewValue = new object (); // temporarily store some values
Int I = 0;
PropertyInfo [] pifs = typeof (T). GetProperties (); // obtain all attributes of the model.
Foreach (var p in pifs)
{
String ControlNameStr = "txt" + p. Name. ToString ();
If (fromTest [ControlNameStr]! = Null) // check whether the corresponding control is null
{
Try
{
NewValue = Convert. ChangeType (fromTest [ControlNameStr], p. PropertyType); // Convert the control value to the value of the corresponding Property
P. SetValue (model, NewValue, null); // set the attribute value
I ++;
}
Catch (Exception)
{
}
}
}
Return model;
}
}
---------------------------- Test this class
Code
InvitationInfo invitioninfo = ModelHeper. modelBind <InvitationInfo> (Request. Form); // The InvitationInfo class is automatically bound to the value on the page.
// Print the attributes of the model.
Type it = typeof (InvitationInfo );
PropertyInfo [] ps = it. GetProperties ();
Object o = new object ();
Foreach (var p in ps)
{
Response. Write (p. Name + "value:" + p. GetValue (invitioninfo, null) + "</br> ");
}