It can be cumbersome using GDI+ to dynamically generate images based on data. I recently had to perform some dynamic image generation within an ASP.NET MVC application, and had the idea of using XAML to define what the image will look like. In a relatively short amount of time, including searching the web and looking at Anoop Madhusudanan’s example, I successfully put together a proper ASP.NET MVC ViewEngine to perform this task.
Download MvcXaml with Samples!
MvcXamlScreenshot <h3>Basics of Usage</h3>
After you register the MvcXaml.XamlImageViewEngine within the Global.asax of your application, you just add the XAML markup file to the Views folder in the same fashion as any other View and write your Controller’s Action methods as normal.
Here’s an example Controller method using MvcXaml: <pre class="csharpcode">public ActionResult Person(int? id) { var model = GetPersonByID(id);

<span class="kwrd">return</span> View(model); }</pre>

As you can see, it’s identical to any other Controller Action. Nothing really different here.

Here’s an example Person.xaml View for this Action:

<UserControl xmlns=""
        Margin="1" Padding="2" Width="300" Height="75"
        <Border BorderBrush="Gray" BorderThickness="2"
                CornerRadius="5" Padding="4">
                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                            <GradientStop Color="White"></GradientStop>
                            <GradientStop Color="LightGray" Offset="1"></GradientStop>
                <StackPanel Orientation="Horizontal">
                    <TextBlock FontWeight="Bold" FontSize="15" Text="{Binding LastName}"/>
                    <TextBlock FontWeight="Bold" FontSize="15">, </TextBlock>
                    <TextBlock FontWeight="Bold" FontSize="15" Text="{Binding FirstName}"></TextBlock>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding ID}"></TextBlock>

This is just normal XAML markup displaying some TextBlock’s and drawing a gradient background.

When used, this is how this example is rendered:



I had ease of use in mind for creating MvcXaml. Building it as a custom ViewEngine not only follows the proper pattern for generating different types of View in ASP.NET MVC, but it also allows it to be used just as any other View. The Controller doesn’t know if you are returning an ASP.NET Web Forms View or a XAML Image View, and keeps with proper separation of concerns.