This article mainly introduces the implementation of form form in the ASP.net to the operation model, this paper imitates the MVC pattern of automatic mapping form of the model, using the generic and reflection implementation, the need for friends can refer to the
We know that asp.net mvc has a powerful place to be when form forms are submitted to an action, you can directly assemble the form's parameters directly into the action's parameter entity object
Like what
The code is as follows:
Action Method Register (Usermodel Usermodel)
{
.............................
}
When submitting a form, the fields inside the form are automatically encapsulated into the corresponding Usermodel field
So WebForm inside can also purple will it?
Because every time to get data, good programmers should learn code encapsulation, code reuse, repetitive work do not do
We can actually use reflection to instantiate objects (automatic assembly)
Well, there's not much nonsense ....
Pageload, it's easy inside.
The code is as follows:
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPost ())
{
Initpage ()//First Access Rendering page
}
Else
{
Usermodel Usermodel = Assemblemodel (base.valuecollection);
}
}
The key is the Assemblemodel method inside the base class.
Base class Inside
We first get the parameters of the context IT404
The code is as follows:
protected NameValueCollection valuecollection = HttpContext.Current.Request.Params;
The base class is simply to store the submitted parameters of the context in the ValueCollection
And then look at the Assemblemodel method, which is a generic method
The code is as follows:
///
Reflection gets the properties of a class
///
///
///
Protected propertyinfo[] Getpropertyinfoarray (type type)
{
propertyinfo[] props = null;
Try
{
Object obj = activator.createinstance (type);
Props = type. GetProperties (BindingFlags.Public | BindingFlags.Instance);
}
catch (Exception ex)
{
}
return props;
}
///
Automatic assembly based on NameValueCollection
///
///
///
///
Protected T Assemblemodel (namevaluecollection valuecollection)
{
propertyinfo[] propertyinfolist = Getpropertyinfoarray (typeof (T));
Object obj = Activator.CreateInstance (typeof (T), null);//Create instance of specified type
foreach (string key in Valuecollection.keys)//value of all contexts
{
foreach (Var propertyinfo in propertyinfolist)//All Entity properties
{
if (key. ToLower () = = PropertyInfo.Name.ToLower ())
{
Propertyinfo.setvalue (obj, Valuecollection[key], NULL);//Assign value to object
}
}
}
Return (T) obj;
}
It's very simple to iterate through the parameters and then use reflection to traverse out the common properties of the entity class and then match and assign the values based on the name names.
So in the future, we just need a code to automatically assemble the values that are saved from the client.
The code is as follows:
Usermodel Usermodel = Assemblemodel (base.valuecollection);