Try-Catch-FAIL

Failure is inevitable.

Exposing the View Model to JavaScript in ASP.NET MVC

clock December 22, 2009 17:24 by author Matt

The prevailing practice for moving data between the controller and the view in ASP.NET MVC applications is to utilize a view model.  While using a view model from within the view’s ASPX page is quite easy, utilizing it from JavaScript can be more complex.  While JavaScript blocks declared inline on the view page can easily consume values from the model, external script files cannot.  In order to take advantage of script batching and minimization, you should avoid the use of inline script blocks and instead use external JavaScript files (.js).  What happens when you need to reference a value from the view model in your JavaScript though?  Since the JavaScript files are not (by default) processed by the ASP.NET pipeline, it isn’t possible for them to leverage the Model; the Model exists server-side, while JavaScript is processed client-side. 

I’ve struggled with this limitation since the first preview release of ASP.NET MVC.  Here are a couple of the approaches that I tried (and hated):

Place scripts in partial views

Instead of following best-practices and placing JavaScript in an external script file, scripts can instead be placed in partial views.  This simplifies the main view by encapsulating the script, and it does allow the script to be re-used.  It also allows the script to easily reference values from the view model. 

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AwesomeViewModel>" %>

<script type="text/javascript">
    
    alert('Hello from the view model: <%=Model.Hello%>');
    
</script>

The downside to this approach is that the script cannot be easily minimized or combined, and it can’t be cached by the browser since it is actually rendered inline in the final markup produced by the view. 

Pass view model properties through an initialization function

Another approach that I’ve used is to define an initialization function within my external JavaScript files.  Any values that are needed by the script can be extracted from the model within the main view, then passed to the external JavaScript through the initialization function.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AwesomeViewModel>" %>
...
<script type="text/javascript" src="ExternalScript.js"></script>
<script type="text/javascript">
    var name = "<%=Model.Name %>";
    ExternalScript_Init(name);
</script>
...

//Contents of ExternalScript.js
ExternalScript_Init(name) {
    alert("Hello from JavaScript: " + name);
}

This approach is also less than ideal.  Any values the script requires must be manually extracted from the view model, which makes maintenance more of a headache than it should be. 

The ideal solution

The previous two approaches “work”, but they each have drawbacks.  The ideal solution would allow the model to be easily consumed by external JavaScript files within a minimal amount of manual work.  Adding a new property to the view model should require zero JavaScript in order to expose the new property for use by scripts.  It turns out that this is actually quite easy to do….

The right way: serialize the model to JavaScript!

.NET 3.5 introduced the JavaScriptSerializer class for serializing objects to/from JSON. With it, most .NET types can be easily converted into a form that’s easily consumable by JavaScript.  Scott Gu introduced a simple ToJSON extension method on his blog which can be used to transform a view model into JSON.  When the output of this method is assigned to a JavaScript variable, the properties of the view model effectively become available to client-side script (note that methods defined on the view model, if any, are ignored by the JavaScriptSerializer). 

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AwesomeViewModel>" %>
...
    <script type="text/javascript">
        var Model = <%=Model.ToJson() %>
        //If needed, new properties can be added to the model, such as URLs for AJAX requests:
        Model.MyAjaxMethod = '<%=Html.BuildUrlFromExpression<MyController>(c => c.DoAjaxyThing()) %>';        
    </script>

The above code block should appear before any scripts that wish to access properties from the view model, which can reference view model properties easily:

<script type="text/javascript">
    
    alert("Hello from the JSON view model:" + Model.Hello);
    
</script>

This is a big improvement over the other two approaches I’ve tried (at least in my opinion), but it still requires me to perform this mundane serialization task on each view.  An easy improvement is to move it to the master page:

<script type="text/javascript">
    var Model = <%=Model != null ? Model.ToJson() : "{}" %>;
</script>

Now every view that has a view model will automatically have a Model object available.

Thoughts?  Suggestions?  Anyone found a better solution that I’ve just overlooked somehow?

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


My best (or worst) MVC hack to date…

clock December 11, 2009 06:40 by author Matt

I really don’t know if I should be proud or embarrassed by what I just implemented.  I’m going to go with “embarrassed”.  If anyone sees a better way to do it, let me know.

The Problem

I have a multi-tab interface (via jQuery UI  tabs).  The view is strongly-typed and has a view model, so it’s decoupled from the domain objects that are used to populate it.  The view is rendered using the MVC Future expression-based input builders, so instead of Html.TextBox(“Blah”), I’ve got Html.TextBoxFor(m => m.Property).  For those that don’t know, the expression-based builders allow you to bind to your view model using expressions instead of magic strings, so you get compile-time safety, rename support, etc.  Anyway, two of the tabs are *almost exactly* the same except for their labels and the underlying object that they’re bound to.  Basically, the original view model looks like this:

public class MySuperViewModel
{
    WidgetViewModel Tab1 { get; set; }
    
    WidgetViewModel Tab2 { get; set; }
}

What I want to do is render the same UI for both FirstTab and SecondTab, have both wired up by ASP.NET automagically, and not have to repeat a bunch of markup.

What doesn’t work

My first though was “oh, I’ll just make a strongly-typed partial view for WidgetTabViewModel, and render it twice!”  That doesn't work though because of how the expression-based input builders work.  They build their IDs based on the expression you pass in.  If I was going to take this approach, inside the partial for the tabs I would be calling this ‘Html.TextBoxFor(m => m.WidgetName)’, which will generate the following markup:

<input name=”WidgetName” … ></input>

Note that there’s nothing in the markup that’s going to let it ASP.NET MVC know where to wire things up in relation to the original view model.  Not good. This is what it needs to look like:

<input name=”Tab1_WidgetName” …></input>

My next thought was “well, I’ll just make a special view model to drive the tab partial view, and pass the expressions in via the view model”, like so:

public class TabViewModel
{
    public Expression<Func<MySuperViewModel, string>> Name;
    
    public Expression<Func<MySuperViewModel, string>> Value;
}

...
//Does not compile, TextBoxFor is actually TextBoxFor<Expression<Func<TabViewModel,object>>
<%=Html.TextBoxFor(Model.Name) %> 

This almost works, but unfortunately the expression-based input builders are defined on HtmlHelper<TModel>, where TModel is your view model type, meaning that the expressions I passed in from the top-level view do not match what TextBoxFor expects as input. 

My horrendous hack/brilliant solution

The fundamental problem is that I want to bind my inputs to expressions as if they were built from the top-level view using its HtmlHelper.  My solution is simple: I just pass in the top-level view’s HtmlHelper view the view model:

public class TabViewModel
{
    public Expression<Func<MySuperViewModel, string>> Name;
    
    public Expression<Func<MySuperViewModel, string>> Value;
    
    //HOT (Hack Or Not)?
    public HtmlHelper<MySuperViewModel> Helper;
}

In the partial view, I can render my inputs and get the correct binding names for MVC using ‘<%=Model.Helper.TextBoxFor(Model.Name))’.  In the master view, I can render the partial view using something like this:

<% Html.RenderPartial("MyTab", new TabViewModel
{
    Name = m => m.Tab1.Name,
    Value = m => m.Tab1.Value,
    Label = "Tab 1",
    Helper = Html
}); %>

I was sort-of surprised when this worked, but it did, and it saved me from having to duplicate about 100 lines of markup.  It still feels dirty though, so if anyone sees a good way to get around this (and I really hope there is), let me know. 

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


A fluent HtmlHelper extension for using FusionCharts in ASP.NET MVC, Part 2

clock December 1, 2009 08:44 by author Matt

Hey, it only took me nearly a month to write part 2 of this series!  Yeah, I’ve been neglecting this blog a lot lately.  There just aren’t enough hours in the day to write. 

In part 1, I discussed charting with ASP.NET MVC and why I decided to use a Flash solution (FusionCharts Free) instead of an ASP.NET control or a JavaScript solution.  Nearly a month later, I’m still very glad I made the switch. 

As I said in part 1, FusionCharts Free includes some methods for working with FusionCharts from ASP.NET, and those work fine in both WebForms and MVC applications.  They aren’t very MVC-like though, and they take quite a few parameters that I don’t want to deal with most of the time.  They also don’t help with building the XML that configures a FusionChart.  The markup the methods generate also suffers from the annoying Flash z-order glitch.  To overcome these limitations, I decided to create some HtmlHelper extensions.  I wanted something that was flexible yet simple.  While I think that fluent APIs have been abused by the .NET community, I do think there are times where they make sense.  When using an HtmlHelper extension, I want to be able to configure the extension without resorting to a code block, which is exactly why I chose to go the fluent route for the FusionCharts helpers.  Before digging into the implementation, let’s take a look at the API in action again.  This is a simple example using an array of numbers, but the API actually supports any object you want to work with:

<%=Html.FusionCharts().Column2D(new[] {1, 2, 3, 4, 5}, 300, 300, d => d)
        .Caption("Numbers")
        .SubCaption("(subcaption)")
        .Label(d => "Label " + d)
        .Hover(d => "Hover " + d)
        .Action(d => "javascript:alert(&apos;You clicked on " + d + "&apos;);")%>

This renders a 2D bar chart, like so:

barChart

All of the methods should be fairly self-explanatory, except perhaps the Action method.  Action allows you to create hyperlinks for the data items in your chart.  In this case, I’ve created a JavaScript link that will display an alert when a bar in the chart is clicked. 

As I said, this API is generic and supports any type.  This allows you to pass in complicated objects that expose values, labels, etc. that can be bound using the various methods exposed on the fluent API. 

Time for some code.  First is the HtmlHelper extension and the entry point to the FusionChart helpers:

/// <summary>
/// Container for the actual extension method.
/// </summary>
public static class FusionChartsHtmlHelper
{
    /// <summary>
    /// Gets a helper for building a fusion chart.
    /// </summary>
    /// <param name="helper"></param>
    /// <returns></returns>
    public static FusionChartsHelper FusionCharts(this HtmlHelper helper)
    {
        return new FusionChartsHelper(helper);
    }
}

/// <summary>
/// An HTML helper for FusionCharts. 
/// </summary>
public class FusionChartsHelper
{
    /// <summary>
    /// The HTML helper.
    /// </summary>
    private readonly HtmlHelper mHtmlHelper;

    /// <summary>
    /// The resolved path to the Fusion Charts SWF files.
    /// </summary>
    private readonly string mChartsFolderBase;

    /// <summary>
    /// Initializes the helper. 
    /// </summary>
    /// <param name="helper"></param>
    public FusionChartsHelper(HtmlHelper helper)
    {
        mHtmlHelper = helper;
        UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

        mChartsFolderBase = urlHelper.Content("~/Charts/");
    }

    /// <summary>
    /// Gets a fusion chart builder that will create a 2D bar chart.
    /// </summary>
    /// <typeparam name="T">The type of the data items.</typeparam>
    /// <param name="data">The items to bind to the chart.</param>
    /// <param name="width">Width in pixels.</param>
    /// <param name="height">Height in pixels.</param>
    /// <param name="getValue">Delegate that extracts the numerical value from a data item.</param>
    /// <returns>A 2D chart builder.</returns>
    public FusionChartColumn2DBuilder<T> Column2D<T>(
        IEnumerable<T> data, 
        int width, 
        int height,  
        Func<T, double> getValue)
    {
        return new FusionChartColumn2DBuilder<T>(mHtmlHelper, mChartsFolderBase, data, getValue, width, height);
    }

    /// <summary>
    /// Creates a builder for 2D pie chart.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <param name="getValue"></param>
    /// <returns></returns>
    public FusionChartPie2DChartBuilder<T> Pie2D<T>(
        IEnumerable<T> data, 
        int width, 
        int height,  
        Func<T, double> getValue)
    {
        return new FusionChartPie2DChartBuilder<T>(mHtmlHelper, mChartsFolderBase, data, getValue, width, height);
    }
}

So far I’ve only implemented two chart builders (one for bar charts, and one for pie charts), but FusionCharts supports a slew of charts that could easily be integrated into this API.

FusionChartsHelper doesn’t do much aside from instantiate the actual chart builders.  These are the fluent APIs for building and configuring a chart.  Let’s look at each of them:

/// <summary>
/// A builder for a 2D column chart.
/// </summary>
/// <typeparam name="T"></typeparam>
public class FusionChartColumn2DBuilder<T> : FusionChartBuilder<T>
{
    /// <summary>
    /// The filename of the chart.
    /// </summary>
    private const string CHART_NAME = "FCF_Column2D.swf";

    /// <summary>
    /// The label for the X axis.
    /// </summary>
    private string mXAxisLabel;

    /// <summary>
    /// The label for the Y axis.
    /// </summary>
    private string mYAxisLabel;

    /// <summary>
    /// Initializes the builder.
    /// </summary>
    /// <param name="helper"></param>
    /// <param name="baseUrl">The URL to the folder that contains the SWF files for Fusion Charts.</param>
    /// <param name="data"></param>
    /// <param name="valueExtractor"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public FusionChartColumn2DBuilder(HtmlHelper helper, string baseUrl, IEnumerable<T> data, Func<T, double> valueExtractor, int width, int height) :
        base(helper, baseUrl + CHART_NAME, data, valueExtractor, width, height)
    {
    }

    /// <summary>
    /// Writes the X and Y axis labels.
    /// </summary>
    /// <param name="xml"></param>
    internal override void WriteGraphProperties(StringBuilder xml)
    {
        if (mXAxisLabel != null) xml.AppendFormat(" xAxisName='{0}'", mXAxisLabel);

        if (mYAxisLabel != null) xml.AppendFormat(" yAxisName='{0}'", mYAxisLabel);
    }

    /// <summary>
    /// Sets the label for the X Axis.
    /// </summary>
    /// <param name="xAxisLabel"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> XAxisLabel(string xAxisLabel)
    {
        mXAxisLabel = xAxisLabel;

        return this;
    }

    /// <summary>
    /// Sets the label for the Y Axis.
    /// </summary>
    /// <param name="yAxisLabel"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> YAxisLabel(string yAxisLabel)
    {
        mYAxisLabel = yAxisLabel;

        return this;
    }
}

/// <summary>
/// A chart builder for 2D pie charts.
/// </summary>
/// <typeparam name="T"></typeparam>
public class FusionChartPie2DChartBuilder<T> : FusionChartBuilder<T>
{
    /// <summary>
    /// The name of the Pie Chart SWF file.
    /// </summary>
    private const string CHART_NAME = "FCF_Pie2D.swf";

    /// <summary>
    /// Flag that controls whether or not labels are shown by pie slices.
    /// </summary>
    private bool mShowLables = true;

    /// <summary>
    /// Initializes the builder.
    /// </summary>
    /// <param name="helper"></param>
    /// <param name="chartUrl"></param>
    /// <param name="data"></param>
    /// <param name="valueExtractor"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public FusionChartPie2DChartBuilder(HtmlHelper helper, string chartUrl, IEnumerable<T> data, Func<T, double> valueExtractor, int width, int height) 
        : base(helper, chartUrl + CHART_NAME, data, valueExtractor, width, height)
    {
    }

    /// <summary>
    /// Writes chart-specific XML settings. 
    /// </summary>
    /// <param name="xml"></param>
    /// <remarks>
    /// Derived classes should override this method to add any chart-specific markup to the
    /// &lt;graph&gt; element.  When called, the '&lt;graph ' markup will have been rendered already.  
    /// </remarks>
    internal override void WriteGraphProperties(StringBuilder xml)
    {
        if (mShowLables) xml.Append(" shownames='1'");
    }

    /// <summary>
    /// Hides the labels from the pie chart.
    /// </summary>
    /// <returns></returns>
    public FusionChartPie2DChartBuilder<T> HideLabels()
    {
        mShowLables = false;

        return this;
    }
}

Each class is fairly short and exposes only the functionality that is specific to its chart type.  All the common functionality and the core of the chart rendering is handled by the base class, FusionChartBuilder<T>: 

/// <summary>
/// Builds a chart.
/// </summary>
public abstract class FusionChartBuilder<T>
{
    ...
    
    /// <summary>
    /// Creates the builder.
    /// </summary>
    /// <param name="data">The data items to build a chart from.</param>
    /// <param name="valueExtractor">Used to get the value from data items.</param>
    /// <param name="helper"></param>
    /// <param name="chartUrl">The URL to the chart.</param>
    /// <param name="width">Chart width.</param>
    /// <param name="height">Chart height.</param>
    public FusionChartBuilder(HtmlHelper helper, string chartUrl, IEnumerable<T> data, Func<T,double> valueExtractor, int width, int height)
    {
        ...
    }

    /// <summary>
    /// Gets the next available color.
    /// </summary>
    /// <returns></returns>
    private string GetNextColor()
    {
        ...
    }

    /// <summary>
    /// Writes chart-specific XML settings. 
    /// </summary>
    /// <param name="xml"></param>
    /// <remarks>
    /// Derived classes should override this method to add any chart-specific markup to the
    /// &lt;graph&gt; element.  When called, the '&lt;graph ' markup will have been rendered already.  
    /// </remarks>
    internal abstract void WriteGraphProperties(StringBuilder xml);

    /// <summary>
    /// Adds an action link to each item. 
    /// </summary>
    /// <param name="actionLink"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> Action(Func<T, string> actionLink)
    {
        ...
    }

    /// <summary>
    /// Sets the ID of the generated chart.
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> Id(string id)
    {
        ...
    }

    /// <summary>
    /// Specify a callback that extracts a friendly label for each item.
    /// </summary>
    /// <param name="getLabel"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> Label(Func<T, string> getLabel)
    {
        ...
    }

    /// <summary>
    /// Enables debug mode.
    /// </summary>
    /// <returns></returns>
    public FusionChartBuilder<T> EnableDebugMode()
    {
        ...
    }

    /// <summary>
    /// Sets the number of decimal places to show.
    /// </summary>
    /// <param name="precision"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> DecimalPrecision(int precision)
    {
        ...
    }

    /// <summary>
    /// When enabled this will round numbers to millions or thousands and add the
    /// corresponding suffix (k for thousands and m for millions).
    /// </summary>
    /// <param name="enabled"></param>
    /// <returns></returns>
    /// <remarks>
    /// Setting this to true corresponds to setting FormatNumberScale='1' on the
    /// graph XML element in FusionCharts.
    /// </remarks>
    public FusionChartBuilder<T> UseDynamicSuffixes(bool enabled)
    {
        ...
    }

    /// <summary>
    /// Sets the value to prepend to all numeric values.
    /// </summary>
    /// <param name="prefix"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> NumberPrefix(string prefix)
    {
        ...
    }

    /// <summary>
    /// Sets the value to append to all numeric values.
    /// </summary>
    /// <param name="suffix"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> NumberSuffix(string suffix)
    {
        ...
    }

    /// <summary>
    /// Builds a string of text to show as a chart item's tooltip.
    /// </summary>
    /// <param name="hoverLabelBuilder"></param>
    /// <returns></returns>
    public FusionChartBuilder<T> Hover(Func<T, string> hoverLabelBuilder)
    {
        ...
    }

    /// <summary>
    /// Renders the chart.
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        //The real work happens here!
        ...
    }

    /// <summary>
    /// Sets the chart caption.
    /// </summary>
    /// <param name="caption"></param>
    public FusionChartBuilder<T> Caption(string caption)
    {
        ...
    }

    /// <summary>
    /// Sets the chart's subcaption.
    /// </summary>
    /// <param name="subCaption"></param>
    public FusionChartBuilder<T> SubCaption(string subCaption)
    {
        ...
    }
}

I’ve omitted the field and property definitions as they’re mundane (and available in the full source below).  The fluent methods are fairly simple and just do the standard “set and return”:

/// <summary>
/// Sets the chart caption.
/// </summary>
/// <param name="caption"></param>
public FusionChartBuilder<T> Caption(string caption)
{
    mCaption = caption;

    return this;
}

The real work occurs in the ToString method.  This method renders the FusionCharts markup and XML configuration data based on the data items and the configuration settings made with the fluent methods.  It also does a quick find-and-replace to correct the z-ordering problem with Flash:

/// <summary>
/// Renders the chart.
/// </summary>
/// <returns></returns>
public override string ToString()
{
    StringBuilder xml = new StringBuilder();

    xml.Append("<graph");

    WriteGraphProperties(xml);

    if (mDecimalPrecision >= 0) xml.AppendFormat(" decimalPrecision='{0}'", mDecimalPrecision);

    if (mUseDynamicSuffixes) xml.AppendFormat(" formatNumberScale='1'");

    if (mPrefix != null) xml.AppendFormat(" numberPrefix='{0}'", mPrefix);

    if (mSuffix != null) xml.AppendFormat(" numberSuffix='{0}'", mSuffix);

    if (mCaption != null) xml.AppendFormat(" caption='{0}'", mCaption);

    if (mSubCaption != null) xml.AppendFormat(" subCaption='{0}'", mSubCaption);

    xml.AppendLine(">");

    foreach (T item in Data)
    {
        xml.AppendFormat("<set value='{0}' color='{1}'", mValueExtractor(item), GetNextColor());

        if (mLabeler != null)
        {
            xml.AppendFormat(" name='{0}'", mHelper.UrlEncode(mLabeler(item)));
        }

        if (mLinkBuilder != null)
        {
            xml.AppendFormat(" link='{0}'", mHelper.UrlEncode(mLinkBuilder(item)));
        }

        if (mHoverLabelBuilder != null)
        {
            xml.AppendFormat(" hoverText='{0}'", mHelper.UrlEncode(mHoverLabelBuilder(item)));
        }

        xml.AppendLine("/>");
    }

    xml.AppendLine("</graph>");

    string markup = InfoSoftGlobal.FusionCharts.RenderChartHTML(mChartUrl, "", xml.ToString(), mChartId, 
                                                                Width.ToString(), Height.ToString(), mDebugEnabled);

    //We have to add another param to make sure the flash object doesn't shine through jQuery UI.
    markup = markup.Replace("<param name=\"quality\" value=\"high\" />",
                            "<param name=\"quality\" value=\"high\" /><param value=\"opaque\" name=\"wmode\" />")
        .Replace("<embed", "<embed wmode=\"opaque\"");

    return markup;
}

Also note that it calls the abstract WriteGraphProperties method, which allows derived classes to inject their own config settings.

Again, this is a pretty bare-bones API right now.  I’ve implemented just the charts and config options that I needed for the project I’m working on, but it could easily be extended with new settings and chart types.  If you’re going to use this in your own project, be sure you put the SWF files for FusionCharts in ‘/Charts’, or edit the hard-coded path in the code (or replace it with a config setting or static property that can be set from Global.asax). 

You can download the code here, graciously donated by InRAD.  Note that I have not tested this code outside of InRAD’s projects, so let me know if I missed a dependency. 

Thoughts?  Suggestions? 

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


A fluent HtmlHelper extension for using FusionCharts in ASP.NET MVC, Part 1

clock November 10, 2009 10:26 by author Matt

We’ve been working like mad to get a (very) functional prototype of our new system running at work, which is why my posts have been rather sparse lately.  We’re doing interesting things, just not much that I can talk about.  Today is different though, I actually have something useful to share!

My current task revolves around rendering charts.  I’ve previously used a variety of charting libraries, mostly recently Telerik and dotnetCharting, but we wanted to go a different route this time.  Neither was a good fit for ASP.NET MVC the last time I looked.  So, I thought I’d pick up one of the many handy JavaScript charting libraries and be done with it.  Unfortunately, that didn’t pan out.  Flot is simply not flexible enough for my needs.  jqPlot was about the same.  Yeah, you can extend either of them, but I wanted something I could customize with less work (basically I wanted more built-in options).  I also looked at the Google solution, but that’s the exact opposite of flexible since it renders as a non-interactive image.  After lots of wailing around, I gave up on the JavaScript route and concluded that none of them are really mature.

I briefly considered Silverlight before deciding that I should see what Flash had available.  Much to my surprise, I found a great little charting library that works well enough with .NET: FusionCharts Free!  Out of all the charting APIs I’ve used over the years, this has quickly become my favorite.  You just feed in an XML definition of what the graph should look like, and it renders it.  It offers a slew of options, too, making it a good fit for what I needed.

Sadly the samples all deal with ASP.NET WebForms and not with ASP.NET MVC.  The same approach works, but I wanted something cleaner.  I decided to create an HtmlHelper extension that would allow me to build a FusionChart with a fluent interface.  Despite my aversion to fluent interfaces, I do think there are times where they make sense, and I think control builders for MVC are a good fit.  My approach when I make a fluent interface is simple: anything that’s required is a parameter of the head method in the fluent chain.  All other optional settings are exposed as fluent methods.  An alternative is to accept some sort of “settings” object that exposes all the settings as properties, and while this does allow for the same terse inline configuration, it’s less readable to me than the fluent version. 

Anyway, let’s look at the usage of this API.  You would call it from your view like any other HtmlHelper:

Html.FusionCharts().Column2D(Model.Data, 415, 247, d => d.TotalSales)
    .Label(d => d.ShortName)
    .Hover(d => d.LongName)
    .XAxisLabel("Widgets")
    .YAxisLabel("Sales")
    .DecimalPrecision(2)
    .UseDynamicSuffixes(true)
    .NumberPrefix("$")
    .Action(d => Html.BuildUrlFromExpression<WidgetController>(c => c.ViewWidget(d=>d.Id)))

Html.FusionCharts() returns a helper class that exposes methods for creating the various chart types (for now, I’ve only implemented the 2D column chart, but plan to do others).  Column2D is the head of the fluent chain and returns a FusionChartBuilder<T>:

/// <summary>
/// Gets a fusion chart builder that will create a 2D bar chart.
/// </summary>
/// <typeparam name="T">The type of the data items.</typeparam>
/// <param name="data">The items to bind to the chart.</param>
/// <param name="width">Width in pixels.</param>
/// <param name="height">Height in pixels.</param>
/// <param name="getValue">Delegate that extracts the numerical value from a data item.</param>
/// <returns></returns>
public FusionChartBuilder<T> Column2D<T>(
    IEnumerable<T> data, 
    int width, 
    int height,  
    Func<T, double> getValue)
{
    return new FusionChartBuilder<T>(mHtmlHelper, mUrlHelper.Content("~/Charts/FCF_Column2D.swf"),
            data, getValue, width, height);
}

The builder enables me to configure options on my charts cleanly from within my view.  I’m not exposing all the FusionChart options yet (and probably won’t), but so far I can control the chart labels, the tooltip that’s shown when you hover over a bar, the format of the numbers, and I can even add a link to each bar, enabling users to “drill-down” into the data or navigate to a corresponding details page.

Time is short, so I’m not going to get any further into the code today, but I will in a future post.  For now, feel free to tell me how you love/hate fluent APIs or what a brilliant/dumb developer I am for using Flash from ASP.NET.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Fluent wrapper for ASP.NET MVC TagBuilder

clock September 8, 2009 07:35 by author Matt

I’m not a huge fan of the fluent-API.  I think it’s a pattern that’s been overused and is now applied like mayonnaise: people are putting it on things where it just doesn’t belong.  That said, there are times when it’s useful.  Case in point is building up an HTML snippet programmatically for use in ASP.NET MVC.  Unfortunately, the handy TagBuilder class actually isn’t fluent (at all).  Most of its methods return void.  Fortunately it is quite easy to adapt the TagBuilder into a fluent version.  Behold, FluentTagBuilder:

/// <summary>
/// Wrapper for <see cref="TagBuilder"/> that makes
/// it a fluent API.
/// </summary>
public class FluentTagBuilder
{
    private TagBuilder mBuilder;

    public FluentTagBuilder(string tagName)
    {
        mBuilder = new TagBuilder(tagName);
    }

    public FluentTagBuilder MergeAttribute(string key, string value)
    {
        mBuilder.MergeAttribute(key, value);

        return this;
    }

    public FluentTagBuilder AddCssClass(string cssClass)
    {
        mBuilder.AddCssClass(cssClass);

        return this;
    }

    public string InnerHtml
    {
        get
        {
            return mBuilder.InnerHtml;
        }
        set
        {
            mBuilder.InnerHtml = value;
        }
    }

    public override string ToString()
    {
        return mBuilder.ToString();
    }
}

Note that I haven’t exposed all the underlying TagBuilder functionality, just the bits I needed today.  Implementing the rest yourself should be trivial though.  Here’s an example use in an HtmlHelper extension:

public FluentTagBuilder SuperSecretButton(string url, string altText)
{
    FluentTagBuilder link = new FluentTagBuilder("a")
        .MergeAttribute("href", url)
        .MergeAttribute("target", "_blank");

    FluentTagBuilder image = new FluentTagBuilder("img")
        .MergeAttribute("src", mHelper.ResolveUrl(SEEKRET_URL))
        .MergeAttribute("alt", altText);

    link.InnerHtml = image.ToString();

    return link;
}

And the use of the helper in the view:

Html.MyHelper().SuperSecretButton("http://wherever", "I am a button").AddCssClass("analyzeCostResearch")

Note how the view can add a class (or potentially any other attribute) without clutering up the method signatures for the helper. 

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Standardizing JSON Responses in ASP.NET MVC

clock August 11, 2009 04:05 by author Matt

ASP.NET MVC provides very nice support for returning JSON data, but my chief complaint with it is that it’s too flexible.  You can basically cram anything you want in it and trust that it will make it to the client script, which has lead to a complete lack of coherence among the various controllers in our big MVC application.  Some actions return a simple string that contains either “success” or “error” depending on whether or not the operation succeeded.  Others return true or false.  This is going to cause maintenance problems down the road, so we are taking a stab at standardizing things.  Right now, the idea is to create a class derived from JsonResult that exposes a few standard properties while at the same time maintaining the flexibility of the original JsonResult.  The common properties are “status”, a boolean that is true or false depending on success or failure of the requested action, and “message”, an optional string that can be set with additional details in the case of failure.  The custom result maintains the ability to insert additional properties into the JSON result via an object (anonymous or otherwise) as well as through adding key/value pairs explicitly.  The implementation is quite simple (commments removed for readability):

public class StandardJsonResult : JsonResult
{
    public string Message { get; set; }

    public bool Status { get; set; }

    public Dictionary<string, object> Properties { get; private set; }

    public StandardJsonResult()
    {
        Properties = new Dictionary<string, object>();
        Data = Properties;
        Status = true;
    }

    public StandardJsonResult(object data)
        : this()
    {
        IDictionary<string, object> properties = data.ToDictionary();

        foreach (var keyValue in properties)
        {
            Properties.Add(keyValue.Key, keyValue.Value);
        }
    }

    public StandardJsonResult(Exception ex) : this()
    {
        Status = false;
        Message = ex.Message;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        //Copy in standard properties
        Properties.Add("status", Status);

        if (Message != null)
        {
            Properties.Add("message", Message);
        }

        base.ExecuteResult(context);
    }
}

There are several constructors provided.  The one that takes an object as a parameter allows you to send anonymous objects or view models across the wire just like you can with a regular JsonResult object.  The values are copied from the object using the method I previous described, but it could also be done using a RouteDataDictionary.  The values are added to the Properties dictionary, which is actually assigned to the JsonResult’s Data property.  The key/value pairs in the dictionary are serialized to properties in the JSON output.  The ExecuteResult method is overridden so that the two standard properties can be added to the dictionary prior to JSON serialization.

This class can also be extended for other recurring scenarios.  For example, here is the custom result that feeds data into liteGrid:

public class LiteGridJsonResult : StandardJsonResult
{
    public Array DataItems { get; private set; }

    public LiteGridJsonResult(Array dataItems)
    {
        DataItems = dataItems;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        Properties.Add("dataItems", DataItems);

        base.ExecuteResult(context);
    }
}

This custom result simply extends the standard one with a collection of data items that will be rendered by the client. 

Thoughts or suggestions?

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC HtmlHelper for Uploadify, Take One

clock May 13, 2009 06:56 by author Matt

As I’ve mentioned before, I really, really hate the way most people seem to be creating reusable UI “controls” with ASP.NET MVC.  I do not like emitting JavaScript, HTML, etc. from within C# code.  It’s cumbersome to create, difficult to really test, and just a real PITA in general.

Based on feedback I received from Rob after my attempts at creating a helper for jqGrid, I decided to take a completely different approach when it was time to wrap another jQuery plug-in: Uploadify.  My goal was to minimize the amount of tag-soup embedded in my C# code while still maintaining the ease-of-use of the jqGrid helper, which required only a single HtmlHelper call to go from nothing to full grid.

Well, one painful afternoon later, I think I’ve arrived at something that makes some sense.  First, I couldn’t completely eliminate the tag soup, but I did minimize it (I think) while still keeping the thing extremely simple to use and (hopefully) maintain.  Let’s start with how you would use it:

<asp:Content ContentPlaceHolderID="HeadContent" runat="server">
    <%=Html.Uploadify("fileInput", 
        new UploadifyOptions
           {
               UploadUrl = Html.BuildUrlFromExpression<SandboxController>(c => c.HandleUpload(null)),
            FileExtensions = "*.xls;*.xlsx",
            FileDescription = "Excel Files",
            AuthenticationToken = Request.Cookies[FormsAuthentication.FormsCookieName] == null ?
                string.Empty :
                Request.Cookies[FormsAuthentication.FormsCookieName].Value,
            ErrorFunction = "onError",
            CompleteFunction = "onComplete"
           }) %>
           
    <script type="text/javascript">
        function onError() {
            alert('Something went wrong.');
        }
        function onComplete() {
            alert('File saved!');
        }
    </script>                                                   
</asp:Content>

The first parameter is the name of the input control to convert to an uploadify control, the second contains all the optional settings you can customize.  I prefer to use an options class like this rather than provide 50,000 overloads.  By using a dedicated options class, I can add new settings without breaking existing code or having to create new overloads.  The options should be fairly self explanatory, but here they are:

/// <summary>
/// Defines all options for <see cref="HtmlHelperExtensions.Uploadify"/>.
/// </summary>
public class UploadifyOptions
{
    #region Public Properties

    /// <summary>
    /// The URL to the action that will process uploaded files.
    /// </summary>
    public string UploadUrl { get; set; }

    /// <summary>
    /// The file extensions to accept.
    /// </summary>
    public string FileExtensions { get; set; }

    /// <summary>
    /// Description corresponding to <see cref="FileExtensions"/>.
    /// </summary>
    public string FileDescription { get; set; }

    /// <summary>
    /// The ASP.NET forms authentication token.
    /// </summary>
    /// <example>
    /// You can get this in a view using:
    /// <code>
    /// Request.Cookies[FormsAuthentication.FormsCookieName].Value
    /// </code>
    /// You should check for the existence of the cookie before accessing
    /// its value.
    /// </example>
    public string AuthenticationToken { get; set; }

    /// <summary>
    /// The name of a JavaScript function to call if an error occurs
    /// during the upload.
    /// </summary>
    public string ErrorFunction { get; set; }

    /// <summary>
    /// The name of a JavaScript function to call when an upload
    /// completes successfully. 
    /// </summary>
    public string CompleteFunction { get; set; }

    #endregion
}

Next, we have the actual HtmlHelper extension method:

/// <summary>
/// Renders JavaScript to turn the specified file input control into an 
/// Uploadify upload control.
/// </summary>
/// <param name="helper"></param>
/// <param name="name"></param>
/// <param name="options"></param>
/// <returns></returns>
public static string Uploadify(this HtmlHelper helper, string name, UploadifyOptions options)
{
    string scriptPath = helper.ResolveUrl("~/Content/jqueryPlugins/uploadify/");

    StringBuilder sb = new StringBuilder();
    //Include the JS file.
    sb.Append(helper.ScriptInclude("~/Content/jqueryPlugins/uploadify/jquery.uploadify.js"));
    sb.Append(helper.ScriptInclude("~/Content/jqueryPlugins/uploadify/jquery.uploadify.init.js"));

    //Dump the script to initialze Uploadify
    sb.AppendLine("<script type=\"text/javascript\">");
    sb.AppendLine("$(document).ready(function() {");
    sb.AppendFormat("initUploadify($('#{0}'),'{1}','{2}','{3}','{4}','{5}',{6},{7});", name, options.UploadUrl,
                    scriptPath, options.FileExtensions, options.FileDescription, options.AuthenticationToken,
                    options.ErrorFunction ?? "null", options.CompleteFunction ?? "null");
    sb.AppendLine();
    sb.AppendLine("});");
    sb.AppendLine("</script");

    return sb.ToString();
}

The helper uses a StringBuilder (yeah, I hate them, and I’m open to suggestions) to include two JavaScript files.  The first is the standard uploadify script, but the second is something custom, which I’ll get to in just a second.    Finally, the helper outputs a call to initUploadify inside of the page load event, passing in all the options that were specified.

And that brings us to that second JavaScript include:

//This is used in conjunction with the HtmlHelper.Uploadify extension method.
function initUploadify(control, uploadUrl, baseUrl, fileExtensions, fileDescription, authenticationToken, errorFunction, completeFunction) {
    var options = {};

    options.script = uploadUrl;
    options.uploader = baseUrl + 'uploader.swf';
    options.cancelImg = baseUrl + 'cancel.png';
    //TODO: Make this an option?
    options.auto = true;
    options.scriptData = { AuthenticationToken: authenticationToken };
    options.fileExt = fileExtensions;
    options.fileDesc = fileDescription;

    if (errorFunction != null) {
        options.onError = errorFunction;
    }

    if (completeFunction != null) {
        options.onComplete = completeFunction;
    }

    control.fileUpload(options);
}

In here, I’ve created a simple JavaScript function that actually calls the uploadify JavaScript plug-in.  By using this method instead of using C# to emit the configuration code directly, I’m cutting out a fair amount of tag soup, and I’m wrapping things up in a way that will be easier to change in the future.  Hopefully.  The down side to this approach is that you have to create a new JavaScript method and include for every plug-in you want to use, but combining the scripts and correctly setting cache headers should reduce the request overhead.

I’m not claiming that this is the best way to do this.  In fact, I really hope it isn’t, because I still don’t like it.  But I think that I like it better than the approach I took for jqGrid.  If you have any suggestions or feedback, please share.  Feel free to tell me that I’m doing things completely wrong.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Using Flash with ASP.NET MVC and Authentication

clock May 13, 2009 01:47 by author Matt

There is a well-known bug in Flash that causes it to completely ignore the browser’s session state when it makes a request.  Instead, it either pulls cookies from Internet Explorer or just starts a new session with no cookies.  GOOD CALL, ADOBE.  And when I say this bug is well-known, I mean it was reported in Flash 8.  It’s still sitting in the Adobe bug tracker.  It has been triaged, it seems to have high priority, yet it remains unfixed.  Again, GREAT job, Adobe. 

Anyway, why should you care?  Well, if you want to use Flash for anything, even something simple like AJAX file uploads with Uploadify, you better hope you don’t need authorization and authentication.  But really, why would you want to authenticate users before letting them upload stuff to your site, anyway?  There’s no possible way that could ever be exploited, right?

If you do decide that security is important (HINT: IT IS), there are some well-known hacks to work around it.  None of them fit well with ASP.NET MVC though.  Just when all seemed lost, I found this post from Ariel Popovsky that saved the day.  I have wrapped his solution up in an easy-to-apply custom AuthorizationAttribute that you can tag to a controller or action method.  Here’s the code:

/// <summary>
/// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
/// around a cookie/session bug in Flash.  
/// </summary>
/// <remarks>
/// Details of the bug and workaround can be found on this blog:
/// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class FlashCompatibleAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The key to the authentication token that should be submitted somewhere in the request.
    /// </summary>
    private const string TOKEN_KEY = "AuthenticationToken";

    /// <summary>
    /// This changes the behavior of AuthorizeCore so that it will only authorize
    /// users if a valid token is submitted with the request.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        string token = httpContext.Request.Params[TOKEN_KEY];

        if (token != null)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);

            if (ticket != null)
            {
                FormsIdentity identity = new FormsIdentity(ticket);
                string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
                GenericPrincipal principal = new GenericPrincipal(identity, roles);
                httpContext.User = principal;
            }
        }

        return base.AuthorizeCore(httpContext);
    }
}

The filter checks the request to see if the authentication ticket was submitted.  If so, it tries to decrypt it, then recreates the IPrincipal that is needed by the base AuthorizationAttribute to do its work.  Just apply it to your controller, make sure Flash is submitted the value of the Forms Authentication cookie, and BAM, everything works.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Simplified unit testing for ASP.NET MVC JsonResult

clock May 7, 2009 01:45 by author Matt

There are quite a few examples floating around on the web that describe how to test your JsonResult objects to make sure the data was correctly packaged.  They all follow the same basic pattern: mock out core ASP.NET objects (such as ControllerContext, HttpResponse, and HttpContext), call JsonResult.ExecuteResult, recover what was written to HttpResponse.Output, and deserialize it.  Sure, this approach works, but in the same manner as cleaning your house out by lighting it on fire.  It’s way overkill.  There’s a much easier way.  For simple objects, just cast JsonResult.Data:

   1: string value = "Hello, there!";
   2:  
   3: JsonResult result = new JsonResult { Data=value };
   4:  
   5: //SURPRISE!
   6: Assert.AreEqual(value, (string)result.Data);

Yeah, that seems fairly obvious.  You don’t even need the explicit cast there, I just threw it in to prove the point.  But what about anonymous types?  Easy:

   1: var value = new { Id=5, Something="Else" };
   2:  
   3: JsonResult result = new JsonResult { Data=value };
   4:  
   5: IDictionary<string,object> data = new RouteValueDictionary(result.Data);
   6:  
   7: Assert.AreEqual(5, data["Id"]);
   8: Assert.AreEqual("Else", data["Something"]);

See, easy! “But what about arrays of anonymous types?!?!?” Do not fret, LINQ to the rescue:

   1: var values = new[]
   2:                  {
   3:                      new { Id = 5, Something = "Else" },
   4:                      new { Id = 6, Something = "New" },
   5:                      new { Id = 7, Something = "Old" },
   6:                  };
   7:  
   8: JsonResult result = new JsonResult { Data = values };
   9:  
  10: IDictionary<string, object>[] data = ((object[]) result.Data).Select(o => new RouteValueDictionary(o)).ToArray();
  11:  
  12: Assert.AreEqual(5, data[0]["Id"]);
  13: Assert.AreEqual(6, data[1]["Id"]);
  14: Assert.AreEqual(7, data[2]["Id"]);
  15: Assert.AreEqual("Else", data[0]["Something"]);
  16: Assert.AreEqual("New", data[1]["Something"]);
  17: Assert.AreEqual("Old", data[2]["Something"]);

Again, easy!

Alright, I know what you’re thinking.  “But Matt, the other solutions are all way more complicated, plus you’re cheating, that isn’t what JsonResult.ExecuteResult is going to do!” Well, you’re half-right, the other solutions are way more complicated, but this is actually simulating precisely what ExecuteResult will do.  Don’t believe me?  Pop it open in Reflector, or just browse the source (man I love Subversion).  It isn’t doing anything magical, it’s just using JavaScriptSerializer.  My solution just cuts out the middle man and doesn’t require you to mock out a bunch of complicated objects.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


ASP.NET MVC: Good in a lot of ways, bad in others

clock February 6, 2009 10:06 by author Matt

I have spent the better part of a week now trying to encapsulate a jqGrid control into something that could be cleanly and easily reused from various ASP.NET views.  In some ways, I think I have met those goals, but in others, I think I have failed miserably.  On the plus side, actually creating a grid is quite easy:

   1: <%=Html.JQGrid("treeTabel",
   2:                 new JQGridOptions 
   3:                     { Caption="Components",
   4:                       DataUrl = Html.BuildUrlFromExpression<SandboxController>(c => c.JQGridTreeViewData((int)ViewData["EstimateId"], null)), 
   5:                       PagerId="PagerId", 
   6:                       IsTreeGrid = true,
   7:                       CellEditEnabled = true,
   8:                     },
   9:                 new[]
  10:                     {
  11:                         new JQGridColumn("id", "ID") { Visible = true, IsExpandColumn = true, Editable = false},
  12:                         new JQGridColumn("ComponentId", "ComponentId") { Visible = false, Editable = false},
  13:                         new JQGridColumn("Name", "Component"),
  14:                         new JQGridColumn("HistoricalCost", "Historical"), 
  15:                         new JQGridColumn("EstimatedCost", "Estimated"), 
  16:                         new JQGridColumn("TargetCost", "Target"),
  17:                         new JQGridColumn("Risk", "Risk") { EditType = "select" ,EditOptions = new[] { "Unassigned:Unassigned", "Low:Low", "Medium:Medium", "High:High"}}, 
  18:                     }) %>

That simple (well, sort-of simple), type-safe code produces this horrible mass of HTML and JavaScript:

   1: <script type='text/javascript'>
   1:  
   2: jQuery(document).ready(function(){
   3: jQuery('#treeTabel').jqGrid({
   4: url: '/Sandbox/JQGridTreeViewData/2',
   5: datatype: 'json',
   6: height: '475px',
   7: colNames:['ID','ComponentId','Component','Historical','Estimated','Target','Risk'],
   8: colModel:[
   9: {name:'id',index:'id',sortable:false,width:1},
  10: {name:'ComponentId',index:'ComponentId',sortable:false,width:1,hidden:true},
  11: {name:'Name',index:'Name',editable:true,sortable:false,width:1},
  12: {name:'HistoricalCost',index:'HistoricalCost',editable:true,sortable:false,width:1},
  13: {name:'EstimatedCost',index:'EstimatedCost',editable:true,sortable:false,width:1},
  14: {name:'TargetCost',index:'TargetCost',editable:true,sortable:false,width:1},
  15: {name:'Risk',index:'Risk',editable:true,sortable:false,width:1,edittype:'select',editoptions:{value:'Unassigned:Unassigned;Low:Low;Medium:Medium;High:High'}}
  16: ],
  17: pager: jQuery('#PagerId'),
  18: rowNum:25,
  19: rowList: [10,25,50,100],
  20: imgpath: '/Content/jQueryPlugins/JQGrid/themes/steel/images',
  21: width:(document.body.clientWidth)*(7/10),
  22: shrinkToFit: true,
  23: caption: 'Components',
  24: loadonce: false,
  25: treeGrid: true,
  26: ExpandColumn: 'id',
  27: treeGridModel: 'adjacency',
  28: cellEdit: true,
  29: cellsubmit: 'clientArray'
  30: }).navGrid('#PagerId',{edit:false,add:false,del:false,search:false,refresh:false})
  31: ;});
</script>
   2: <table id='treeTabel' class='scroll'></table>
   3: <div id='PagerId' class='scroll' style='text-align:center;'></div>

Obviously that's a step up.  But when you look under the covers, things are anything but clean and neat.  Basically, I have several methods that build up a bunch of JavaScript strings, then spit them back out.  It reminds me *so* much of old-school PHP, where you have this awful mix of presentation markup and PHP code interwoven together into a blanket that looks like someone threw up on it.  Here's an excerpt:

   1: if (options.IsTreeGrid)
   2: {
   3:     JQGridColumn expandColumn = columns.FirstOrDefault(c => c.IsExpandColumn);
   4:  
   5:     if (expandColumn == null)
   6:     {
   7:         throw new InvalidOperationException("IsTreeGrid is true, but no column found with IsExpandColumn set to true.");
   8:     }
   9:  
  10:     js.AppendLine("treeGrid: true,");
  11:     js.AppendFormat("ExpandColumn: '{0}',", expandColumn.Name).AppendLine();
  12:     js.AppendLine("treeGridModel: 'adjacency',");
  13: }
  14:  
  15: //If cell editing is enabeled, the changed rows are stored client-side,
  16: //and it is the responsibility of the page to provide a mechanism
  17: //for posting the data back.
  18: if (options.CellEditEnabled)
  19: {
  20:     js.AppendLine("cellEdit: true,");
  21:     js.AppendLine("cellsubmit: 'clientArray',");
  22: }

So, I'm torn.  Overall, I think the ASP.NET MVC approach is much, much better than the WebForms approach, but... is this it?  Is this really the best we can do?  There has to be a better way to do things like this.  There has to be a way to keep languages separate.  There has got to be a cleaner way to encapsulate and reuse "controls" in ASP.NET MVC.  I just haven't found it yet.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


About Matt

I am an overworked (and apparently overpaid) software developer with aspirations of acquiring a PhD in Computer Science. I started off coding in C over a decade ago.  Since then, I've migrated from C to C++ and branched out to C#, PHP, VB.NET, JavaScript, and worked with a wide assortment of other languages that I hope to never deal with again (I'm looking at you, COBOL). Oh, and yes, I've written some Java.  Does that make me a bad person?

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2009

Sign in