Example code Analysis for ASP. NET using reflection to assign values to the model class

Source: Internet
Author: User
This article mainly introduces the method of using the reflection to realize the assignment of the model class, and analyzes the operation steps and the related operation skill of ASP to use the reflection to the model class.

The example in this article describes how ASP. NET uses reflection to implement the method of assigning a value to the model class. Share to everyone for your reference, as follows:

<summary>///automatically assigns a value to the Model class//</summary>///<param name= "SqlString" > Gets the SQL statement that queries a model instance </ param>///<param name= "obj" >model instance object </param>///<returns></returns>public Object Selmodel (string Sqlstring,object obj) {DataTable Dtsell = lcommonbll.  GetTable (SqlString); int count = Dtsell.  Rows.Count;  if (count = = 0) {return null; } else {DataRow Dr = Dtsell.   Rows[0]; #region Another method//foreach (DataColumn col in Dr. Table.columns)//{//PropertyInfo pt = seller. GetType (). GetProperty (Col.   ColumnName); if (String.IsNullOrEmpty (Dr[col. ColumnName].   ToString ()))//{//break; }//else//{//PT. SetValue (seller, Dtsell.   ROWS[0][0], NULL); }//} #endregion foreach (System.Reflection.PropertyInfo pi in obj. GetType (). GetProperties ()) {if (pi). CanWrite) {try {if (Dtsell). Rows[0][pi. Name]!=null) {pi. SetValue (obj, Dtsell. Rows[0][pi.      Name], NULL);       } else {Pi.      SetValue (obj, null, NULL); }} catch {pi.     SetValue (obj, null, NULL);  }}} return obj; }}

. CS Call

Seller Seller = new Seller ();//entity class bind Bind = new bind ();//bind method Class Seller = (Seller) bind.selmodel ("select * from Seller where sid=2 ", seller);//Assignment
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.