Friday, 1 July 2011

ASP.NET MVC - Report Generation from .ASPX Files

You can easily use the ASP.NET MVC view engines to create static HTML files or custom HTML reports from, for example, .ASPX and .ASCX files - no need to use some other template system!

Here's a simple example:

    public string Generate(ViewDataDictionary viewData, string templateFile, string masterFile,
            ControllerContext controllerContext)
        var writer = new StringWriter();
        var tempData = new TempDataDictionary();

        var viewResult = ViewEngines.Engines.FindView(controllerContext, templateFile, masterFile);

        if ((viewResult == null) || (viewResult.View == null))
            Log.WriteLine("Generate: ERROR - View not found, template file: '{0}', master file: '{1}",
                templateFile, masterFile);
            return "View not found";

        var viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, writer);
        viewResult.View.Render(viewContext, writer);

        return writer.ToString();

The viewData argument is used to pass in your model, e.g.

    var model = new MyReportViewModel(xxx, yyy);
    var viewData = new ViewDataDictionary(model);

I usually keep the .ASPX and .ASCX fies in a separate subtree of the Views folder.

No comments:

Post a Comment