开发者

Export to xml in asp.net mvc

开发者 https://www.devze.com 2023-02-19 10:25 出处:网络
Anybody know how to perform export functio开发者_如何转开发nality for a perticular view in asp.net mvc?

Anybody know how to perform export functio开发者_如何转开发nality for a perticular view in asp.net mvc? I want export data in xml format. Thanks in advance


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);
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消