Export data into XML from MVC in ASP.NET MVC

How to export data into XML from ASP.NET MVC?

To export data into XML in ASP.NET, we can follow below approach.
CONTROLLER ACTION METHOD
public void ExportToXML()
       {
            var data = db.PersonalDetails.ToList();

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;
filename=itfunda.xml");
            Response.ContentType = "text/xml";

            var serializer = new
System.Xml.Serialization.XmlSerializer(data.GetType());
            serializer.Serialize(Response.OutputStream, data);
       }
In the above action method, we are getting the data from the database and setting almost same properties of the Response object that we have set into previous post.
The changes are following
  • we are changing the name of the file to download
  • setting the ContentType to “text/xml”
  • using XmlSerializer to Serialize the data into XML and sending to the Response OutputStream.
Calling above method from browser like http://localhost:63087/ExportData/ExportToXML gives below output in which browser asks to Open or Save the xml file.

The output file looks like below
OUTPUT

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...