Skip to main content

Xaml Meets ASP.NET MVC – Create databound visualizations with Xaml + ASP.NET MVC using XamlAsyncController

For some time, I was thinking about leveraging the power of Xaml to create databound images/visualizations in web applications, and did a quick POC implementation of the same. Here is the demonstration. We’ll start from the final output, and see how quickly you can render a Xaml control as an image from your ASP.NET MVC Controller – after binding that to your ViewData or view model.

[+] Related Code: Go get it, from codeplex

Generating data bound images using Xaml

The gist of this article is how you can create dynamic or data bound images from Xaml user control. When I mention dynamic or data bound image - what I mean is, taking a snapshot of your Xaml user controls that are bound to the view data or view model. So that, your images will be generated based on the view data/model.

How to do this? The related source code (find the link above) contains a XamlAsyncController implementation, to make the whole task easier in ASP.NET MVC.

Let us go through an example - If you see, there are two images in the below web page – and in this case, both images are generated from Xaml files.


The Views\Home\Index.aspx view that generates the above page is as below.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: ViewData["Message"] %></h2>
    <image src="/Home/ShowMessage" />
    <h2>A simple dashboard</h2>
     <image src="/Dashboard/Chart" />


How to render a Xaml from the Controller?

Now, let us see how you can use XamlAsyncController to implement Xaml image rendering in your own ASP.NET application.

If you see the aspx code above, you may note that the first image is generated by the action ShowMessage in Home Controller, and the second image is generated from the Chart action in Dashboard controller. To render a Xaml Usercontrol as an image, basically you need to do two things.

1 – Inherit your Controller from XamlAsyncController, and add an Async action for serving the image

You need to create a reference from your ASP.NET MVC to the MvcXamlController.Lib (included in the download below).

For example, let us see how the ShowMessage action is implemented for serving the image. If you look at the HomeController, you can see that the HomeController is inherited from XamlAsyncController, a custom abstract controller I implemented, inheriting from AsyncController, that’s already there in ASP.NET MVC 2 (Read about using Asynchronous Controller if you are not familiar with Asynchronous controllers). You just call StartRendering() method in your ShowMessageAsync, and return XamlView() in your ShowMessageCompleted.

    public class HomeController : XamlAsyncController
        public void ShowMessageAsync() 
            ViewData["Message"] = "Welcome from Xaml in MVC";

        public ActionResult ShowMessageCompleted()
            return XamlView();

2 – Add your Xaml file to the path /Visualizations/{Controller}/{Action}.xaml

Once you have your controller’s action to serve an image as above, the next step is to add a Xaml file. Before that, you should  It should be in the path /Visualizations/{Controller}/{Action}.xaml (This is synonymous to adding a View in the path /Views/{Controller}/{Action}.aspx

SideNote: This is going to be a bit tricky. First thing is, you need to add references to WindowsBase, PresentationUI, PresentationCore dlls to your ASP.NET MVC project, which is already done in the demo project. Then you need to manually copy a xaml file from some where else to the required path, as Visual Studio ‘Add New Item’ dialog box won’t display xaml files when you try to add a new item inside your ASP.NET MVC Project.

See how I’m placing the ShowMessage.xaml, under the Visualizations\Home folder.


And you are done. XamlAsyncController is smart enough to fetch the xaml file from the location /Visualizations/{Controller}/{Action}.xaml by convention, and render it as an image. And of course, in your Xaml, you can bind to the ViewData. Let us have a look into our ShowMessage.xaml

<UserControl x:Class="MvcXamlController.Demo.Visualizations.Home.ShowMessage"
        Margin="1" Padding="2" Width="300" Height="60"
        <Border BorderBrush="Gray" BorderThickness="2"  
                Background="WhiteSmoke" CornerRadius="5" Padding="4">
            <TextBlock Text="I am a WPF control rendered as image"/>
            <TextBlock Text="{Binding Message}"/>
And you can find that we are binding to the Message element we pumped into the ViewData, from the controller. This is generating the first image in the rendered html file.

Another Example – A Simple Chart Image

Now, let us see how to create a simple chart in Xaml, based on your viewmodel data?.

Let us add a new Controller to our ASP.NET MVC App, DashboardController.cs. And we have an async action, named Chart. See that we are using an overload of StartRendering to pass some dummy view model data.

public class DashboardController : XamlAsyncController
        public void ChartAsync()
            var items=new List<Item>()
                new Item{Name="Windows7", Region="US", SalesNo=100 },
                new Item{Name="Office2010", Region="US", SalesNo=70 },
                new Item{Name="Sharepoint", Region="US", SalesNo=20 },

        public ActionResult ChartCompleted()
            return XamlView();   


And yes, we have our Chart.xaml in the location /Visualizations/Dashboard/Chart.xaml – and here is how it looks like.

    <UserControl x:Class="MvcXamlController.Demo.Visualizations.Dashboard.Chart"
    <Grid Background="WhiteSmoke">
        <ItemsControl ItemsSource="{Binding .}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <StackPanel HorizontalAlignment="Left">
                    <TextBlock Text="{Binding Name}" 
                               HorizontalAlignment="Left" Height="24" />
                    <Rectangle HorizontalAlignment="Left" 
                               Width="{Binding SalesNo}" Height="10" Fill="Red"/>

More Thoughts And Going Forward

We havn’t yet explored the actual implementation of my XamlAsyncController, and that is for another post. If you are so curios, you can definitely have a look at the source related code.

And remember, this is an experimental implementation, with few hacks here and there. There are various cases that needs to be addressed – for example, the rendering will not be proper for elements that has some loading animation etc. Also, I havn’t yet run this outside the ASP.NET Development server, and hasn’t really done any performance analysis.  How ever, I think this is a good start towards exploring how we can leverage Xaml in web applications.

[Note: Read Part II about this]

Laurent Bugnion also blogged about some of his thoughts about rendering Xaml from server side, how ever I still need to have a look into his code.

Also, Keep in touch :) follow me in twitter or subscribe to this blog.

Interested in ASP.NET MVC? Read my articles about creating a custom view engine for ASP.NET MVC or using Duck Typed View Models in ASP.NET MVC

Popular posts from this blog

MVVM - Binding Multiple Radio Buttons To a single Enum Property in WPF

I had a property in my View Model, of an Enum type, and wanted to bind multiple radio buttons to this.

Firstly, I wrote a simple Enum to Bool converter, like this.

public class EnumToBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (parameter.Equals(value)) return true; else return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return parameter; } #endregion }

And my enumeration is like

public enum CompanyTypes { Type1Comp, Type2Comp, Type3Comp } Now, in my XAML, I provided the enumeration as the ConverterParameter, of the Converter we wrote earlier, like

Creating a quick Todo listing app on Windows using IIS7, Node.js and Mongodb

As I mentioned in my last post, more and more organizations are leaning towards Web Oriented Architecture (WOA) which are highly scalable. If you were exploring cool, scalable options to build highly performing web applications, you know what Node.js is for.After following the recent post from Scott Hanselman, I was up and running quickly with Node.js. In this post, I’ll explain step by step how I’ve setup Node.js and Mongodb to create a simple Todo listing application.Setting up Node.jsThis is what I’ve done.1 – Goto, scroll down and download node.exe for Windows, and place it in your c:\node folder2 – Goto IIS Node project in Git at, download the correct ‘retail’ link of IIS Node zip file (I downloaded the already built retail package, otherwise you can download and build from the source).3 – Extract the zip file some where, and run the install.bat or install_iisexpress.bat depending on your IIS Version. If you don’t have IIS in…

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…