0

Anybody know how to perform export functionality for a perticular view in asp.net mvc? I want export data in xml format. Thanks in advance

2 Answers 2

3

I would use a custom action result:

public class XmlResult : ActionResult
{
    private readonly object _data;
    public XmlResult(object data)
    {
        _data = data;
    }

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

and then you could define a view model which will represent your data:

public class MyViewModel
{
    [XmlElement("product")]
    public ProductViewModel[] Products { get; set; }
}

public class ProductViewModel
{
    [XmlAttribute("id")]
    public int Id { get; set; }
    public string Name { get; set; }
}

and return this view model from the controller action:

public ActionResult Export()
{
    var model = new MyViewModel
    {
        Products = new[]
        {
            new ProductViewModel { Id = 1, Name = "item 1" },
            new ProductViewModel { Id = 2, Name = "item 2" },
            new ProductViewModel { Id = 3, Name = "item 3" },
        }
    };
    return new XmlResult(model);
}
Sign up to request clarification or add additional context in comments.

1 Comment

hi Darin.Thanks a lot for your help.it will be helpful for me.
0

Assuming you only want to export the data and not the actual view.

Make a method in your controller that accepts the same parameters as the one you use for your view, serialize the object(s) and return the resulting xml.

  using System.Xml;
  using System.Xml.Serialization;

MSDN serializer documentation

The simpler answer is to make a view without the call to the masterpage and handcraft the xml there and treat it as any other aspx-page

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.