zarko.susnjar
zarko.susnjar

Reputation: 2053

Best practice for returning XML data in ASP.net MVC2

I was wondering what is best way to create XML output from MVC2 application and return it to client ( possibly also using XSD scheme validation) ?

I know i can't return it directly from controller or pass to view as variable etc. Huge part of my application is doing conversion between different XML sources, schemas and formats so it's really important that I setup this right from the beginning.

But is there any better way to do it?

Thanks in advance!

Upvotes: 0

Views: 1071

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You could write a custom ActionResult which will serialize the view model into XML. Something among the lines:

public class XmlResult : ActionResult
{
    private readonly object _model;
    public XmlResult(object model)
    {
        _model = model;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (_model != null)
        {
            var response = context.HttpContext.Response;
            var serializer = new XmlSerializer(_model.GetType());
            response.ContentType = "text/xml";
            serializer.Serialize(response.OutputStream, _model);
        }
    }
}

and then:

public ActionResult Foo()
{
    SomeViewModel model = ...
    return new XmlResult(model);
}

Feel free to perform any XSD validations, etc... that you might need inside the ExecuteResult method.

As suggested by @Robert Koritnik in the comments section you could also write an extension method:

public static class ControllerExtensions
{
    public static ActionResult Xml(this ControllerBase controller, object model)
    {
        return new XmlResult(model);
    }
}

and then:

public ActionResult Foo()
{
    SomeViewModel model = ...
    return this.Xml(model);
}

This being said if you find yourself in the need of exchanging lots of XML you might consider using WCF. And if you need POX, consider WCF REST.

Upvotes: 4

Related Questions