Home > ASP.NET MVC > Output XML Using Strongly Typed Views in ASP.NET MVC

Output XML Using Strongly Typed Views in ASP.NET MVC

Recently I had to create an export to XML functionality in an ASP.NET MVC application. The first thing that came up to my mind was to use LINQ to XML to serialize my entity and then write it to the output stream with the FileStreamResult class. It could not be much more easy, right? But what is really a single HTML page – one irregular XML document (XHTML is well formed XML). Then I give it a thought and realized that I could use a strongly typed view for my entity and have it change its content type to text/xml.

XML View

Here is my sample User class that would be used to generate the XML file:

public class User
{
    [Required(ErrorMessage = "First Name is required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    public string LastName { get; set; }

    public string Street { get; set; }
    public string City { get; set; }

    [Required(ErrorMessage = "Country is required")]
    public string Country { get; set; }

    public string PhoneNumber { get; set; }

    [Required(ErrorMessage = "Email Address is required")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Age is required")]
    [Range(0, 100, ErrorMessage = "Age must be between 0 and 100")]
    public int Age { get; set; }
}

In Solution Explorer right click on your view folder and choose Add > View. On the following dialog enter the name of the view and check the Create a strongly-typed view checkbox which enables you to select a view data class. Finally click on the Add button and you have created the view.

Now you are ready to edit its contents. The first thing you need to do is to change the ContentType attribute of the Page directive to text/xml:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ExportToXml.Models.User>" ContentType="text/xml" %>

This way you tell your ASP.NET MVC application to change the response header for this resource. The client’s browser would parse it and render the document as XML since it knows how to handle such type of resources.

Replace any other generated content with the XML you want to output. This is what the XML markup for my entity looks like:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ExportToXml.Models.User>" ContentType="text/xml" %><?xml version="1.0" encoding="utf-8" ?>
<User>
    <FirstName><%= Model.FirstName %></FirstName>
    <LastName><%= Model.LastName %></LastName>
    <Street><%= Model.Street %></Street>
    <City><%= Model.City %></City>
    <Country><%= Model.Country %></Country>
    <PhoneNumber><%= Model.PhoneNumber %></PhoneNumber>
    <EmailAddress><%= Model.EmailAddress %></EmailAddress>
    <Age><%= Model.Age %></Age>
</User>

As you can see it’s all really simple, no rocket science. Just be sure to put the declaration of the XML right after the page directive (not on a new line) otherwise it won’t be parsed properly by the browser.

Action Method

The action method responsible for returning the XML document has a return type of ActionResult and calls the View helper method passing the name of the view and the entity that would be exported:

[HttpPost]
public ActionResult Export()
{
    User user = HttpContext.Cache["user"] as User;
    if (user == null)
        return View("Index");

    return View("User", user);
}

As you can see if there is no user in the cache the default view is rendered, otherwise the strongly typed XML view is rendered passing the user entity instance.

Putting It All Together

Now that we have created this we can create an user and then export it. This is what the create user page looks like:

Create User

Create User

After the user is created clicking on the Export button will call the Export action method which will render the strongly typed XML view. The generated XML is the following:

Generated XML

Generated XML

Summary

Using this technique is really simple and makes your code more readable and maintainable because you are relying on declarative code. If you need to make a change you just edit your view’s aspx page and you are ready – no need to recompile and redeploy on the production server. Keep in mind that this solution might not be applicable to your scenario – it is just one way to solve a problem. In a future post I will show you how you can make the browser show a Save As dialog with a specific file name (very useful in some situations).

You could download this sample application from here.

Categories: ASP.NET MVC
  1. June 17, 2010 at 10:31 pm

    Hi,

    Good article, just some notes:

    ‘Manually’ declaring the XML schema may be a good thing or a bad thing. You duplicate object properties with xml declaration (i.e. you are repeating yourself when defining the properties). If you change one of them, most probably you will want to change the other too. In the example you have given, it definitely looks like a bad thing, as you simply want to output the XML serialized object. If you gave a more complex example, where the object is just a part of a grand XML schema, that would make sense.

    Have you considered using XmlResult from MvcContrib?

    Also, HttpContext.Cache[“user”] looks wrong. I don’t have MVC handy but I think the controller provided some property for temporary storing objects 😀

    Cheers!

  2. July 13, 2014 at 2:52 pm

    nice article i like it good great work good luck

  1. June 22, 2010 at 6:31 am

Leave a comment