Thursday 4 April 2013

web programming in asp.net (Code Snippets - 1)


Here am sharing the two small code snippets which every web programmer should know.

Code – I
Btw, have u think of throwing a file output rather than Response.Write(“Hello”); from the browser. Use the following code for this purpose.
string outputFilePath = Server.MapPath(“Feed.xml”);
Response.ContentType = “text/xml”;
Response.AddHeader(“Content-Disposition”, “attachment;filename=\”" + outputFilePath + “\”");
Response.TransmitFile(outputFilePath);
Response.End();
Code – II
Already you may aware of the JSON format, In order to convert a C# Generic List to JSON string and vice-versa.  Follow the below steps
1) Add reference to System.Web.Extensions in your project.
// Assume that you have a generic list as shown below,
// List<Student> studentList = GetStudentList();
2) Use Serialize method in JavaScriptSerializer class for serializing generic list to JSON string.
// System.Web.Script.Serialization.JavaScriptSerializer studentSerializer =  new System.Web.Script.Serialization.JavaScriptSerializer();
3) Use Serialize method to convert patient list to JSON string.
// string JStr = studentSerializer.Serialize(studentList);
4) Now, the json string can be set to generic list of type patient as shown below,
//   List< Student > nList = new List< Student >();
//  nList = studentSerializer.Deserialize<List< Student > >(JStr);
Happy Coding :)

No comments:

Post a Comment