This article illustrates the method of asp.net implementation using reflection, generics, static method to quickly get form value to model. Share to everyone for your reference, specific as follows:
This is the primary, very simple, the cow can not read. But it's practical.
In a project, you often need to work with forms, assign values to the model, and do some repetitive code that is annoying. Like the following code:
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"));
Often there will be errors in writing, especially when writing this boring code of overtime ...
Using reflection, generics, static methods can easily solve this problem. It seems a bit advanced, actually super simple. See Code.
public static class henqpost<t> where T:new ()
{
///<summary>
///for model assignment
///</ 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 T, namevaluecollection form)
{
int va=0;
Type type = T.gettype ();//Get Types
propertyinfo[] Pi=type. GetProperties ()//Get Property Collection
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 a property and convert the type of the key value to the type
of the property va++;//the number of attributes successfully assigned to the record
}
catch {}}} return
va;
}
Only therefore uses the static method, mainly is the diagram convenient, does not need new.
All the forms can be handled very simply, and two lines of code are done.
News = new News ();
Henqpost<news>. Getpost (ref news, Request.Form);
It's annoying to assign values to entity classes over.
No configuration required, the Convention is the best configuration.
Convention: The name of the form item is best matched with the attribute name of the entity class (if you are otherwise, the reflection method is modified according to its own rules).
For the form to assign value, if it is WebForm can also take this way, you can write their own, the principle is similar.
I hope this article will help you to ASP.net program design.