ASP. NET TypeConverter

Source: Internet
Author: User

TypeConverter is no longer familiar with compiling ASP. NET Server Control. The following example shows how to use custom TypeConverter in Atlas.

The role of the JavaScriptConverter class is to provide developers with the ability to customize serialization and deserialization. This is especially important for operations on complex objects that contain circular references. The functions of this class in RTM Release are simplified. Its methods and attributes are reduced to three:

1. IEnumerable <Type> SupportedTypes: Read-only attribute. All classes supported by this Converter are returned.

2. object Deserialize (IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer ):

The first parameter of this method is a Dictionary. Some friends may think that the Dictionary is very close to the JSON String Representation: It is nested by Dictionary and List, the bottom element is some basic type objects. But not in fact. ASP. net ajax deserialization of a json string, if "{" _ type ":"... ",...} "When a segment is converted to a JSON Dictionary, only the Dictionary of the basic type object exists.) If the Dictionary contains the Key" _ type, then we will try to convert it to the type represented by the _ type value at this time. That is to say, the first parameter dictionary accepted by the JavaScriptConverter Deserialize method may already be of a special type.

The second parameter is the conversion target type. The third parameter is the JavaScriptSerializer that calls the current Deserialize method. Some of our deserialization operations can be delegated to it for execution. It has already been associated with the JavaScriptConverter configured in web. config. However, it should be noted that you must avoid returning to the current Deserialize method without any change in the next operation. Obviously, this will lead to an endless loop.

3. IDictionary <string, object> Serialize (object obj, JavaScriptSerializer serializer): the function of this method is relatively pure. The obj object is converted into an IDictionary <string, object> object, ASP. net ajax will add the "_ type" value to this Dictionary. In this way, the current JavaScriptConverter can be used for reverse operations during deserialization.

First, define a complex type:

 
 
  1. [TypeConverter(typeof(EmployeeConverter))]  
  2. public class Employee  
  3. {  
  4. public string Name;  
  5. public int Age;  

We can see that TypeConverterAttribute is used to associate the EmployeeConverter described later with the Employee.

Next, like in the previous example, we write a Web Services method that supports http get access, but the parameters use complex types.

 
 
  1. [WebService(Namespace = "http://tempuri.org/")]  
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  3. public class HttpGetEmployeeService  : System.Web.Services.WebService {  
  4.  
  5. [WebMethod]  
  6. [WebOperation(true, ResponseFormatMode.Xml)]  
  7. public XmlDocument SubmitEmployee(Employee employee)  
  8. {  
  9. XmlDocument responseDoc = new XmlDocument();  
  10. responseDoc.LoadXml(  
  11. "<?xml-stylesheet type=\"text/xsl\" href=\"Employee.xsl\"?>" +  
  12. "<Employee><Name></Name><Age></Age></Employee>");  
  13. responseDoc.SelectSingleNode("//Name").InnerText = employee.Name;  
  14. responseDoc.SelectSingleNode("//Age").InnerText = employee.Age.ToString();  
  15. return responseDoc;  
  16. }  

Then there is the required Xslt file:

 
 
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <xsl:stylesheet version="1.0" 
  3. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
  4. <xsl:template match="/Employee"> 
  5. <html> 
  6. <head> 
  7. <title>Thanks for your participation</title> 
  8. </head> 
  9. <body style="font-family:Verdana; font-size:13px;"> 
  10. <h4>Here's the employee you submitted:</h4> 
  11. <div> 
  12. <xsl:text>Name: </xsl:text> 
  13. <xsl:value-of select="Name" /> 
  14. </div> 
  15. <div> 
  16. <xsl:text>Age: </xsl:text> 
  17. <xsl:value-of select="Age" /> 
  18. </div> 
  19. </body> 
  20. </html> 
  21. </xsl:template> 
  22. </xsl:stylesheet>  

The above should be very familiar to those who have read the previous article. Next, let's go to the topic and define a EmployeeConverter. The Code is as follows:

 
 
  1. public class EmployeeConverter : TypeConverter  
  2. {  
  3. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)  
  4. {  
  5. if (sourceType == typeof(String))  
  6. {  
  7. return true;  
  8. }  
  9.  
  10. return false;  
  11. }  
  12.  
  13. public override object ConvertFrom(ITypeDescriptorContext context, 
    CultureInfo culture, object value)  
  14. {  
  15. IDictionary<string, object> dictObj =  
  16. JavaScriptObjectDeserializer.DeserializeDictionary(value.ToString());  
  17.  
  18. Employee emp = new Employee();  
  19. emp.Name = dictObj["Name"].ToString();  
  20. emp.Age = (int)dictObj["Age"];  
  21.  
  22. return emp;  
  23. }  

EmployeeConverter inherits TypeConverter. First, overwriting the CanConvertFrom method indicates that the use of EmployeeConverter can convert a String to another object. Then, overwrite the ConvertFrom method and convert the passed value into a complex object: Employee. For convenience, we serialize the Employee object on the client JOSN and then serialize it back on the server. In fact, this basic type can be converted to a complex type in any way.

The code is very simple and easy to understand, so let's take a look at the code. Since there are few codes, Javascript and HTML are pasted together:

 
 
  1. <html xmlns="http://www.w3.org/1999/xhtml" > 
  2. <head> 
  3. <title>Convert Primitive Object using Customized TypeConverter</title> 
  4. <script language="javascript"> 
  5. function submitEmployee()  
  6. {  
  7. var emp = new Object();  
  8. emp.Name = $("txtName").value;  
  9. emp.Age = parseInt($("txtAge").value, 10);  
  10.  
  11. var serializedEmp = Sys.Serialization.JSON.serialize(emp);  
  12. var url = "HttpGetEmployeeService.asmx?mn=SubmitEmployee&employee=" + 
    encodeURI(serializedEmp);  
  13. window.open(url);  
  14. }  
  15. </script> 
  16. </head> 
  17. <body style="font-family:Verdana; font-size:13px;"> 
  18. <form runat="server"> 
  19. <atlas:ScriptManager ID="ScriptManager1" runat="server" /> 
  20.  
  21. <div>Name:<input type="text" id="txtName" /></div> 
  22. <div>Age:<input type="text" id="txtAge" /></div> 
  23. <input type="button" value="Submit" onclick="submitEmployee();" /> 
  24. </form> 
  25. </body> 
  26. </html> 

After the "Submit" button is laid, the submitEmployee function is called. This function constructs an Employee object based on user input and then uses it. The preceding section describes ASP. NET TypeConverter.

  1. WebRequestExecutor in ASP. NET
  2. IIS6 ASP. net isapi request processing process
  3. Backup in ASP. NET
  4. Introduction to ASP. NET ISAPI
  5. Iis isapi extension of ASP. NET

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.