MvcXaml - Images from XAML within ASP.NET MVC Application
Jan 9, 2011 • ASP.NETIt 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!
## Basics of Usage
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="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Margin="1" Padding="2" Width="300" Height="75" mc:Ignorable="d"> <Grid> <Border BorderBrush="Gray" BorderThickness="2" CornerRadius="5" Padding="4"> <Border.Background> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="White"></GradientStop> <GradientStop Color="LightGray" Offset="1"></GradientStop> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.Background> <StackPanel> <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> <StackPanel Orientation="Horizontal"> <TextBlock>ID:</TextBlock> <TextBlock Text="{Binding ID}"></TextBlock> </StackPanel> </StackPanel> </Border> </Grid> </UserControl>
This is just normal XAML markup displaying some TextBlock’s and drawing a gradient background.
When used, this is how this example is rendered:
Conclusion
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.