Steve Michelotti

A .NET Developer's Toolbox

  Home  |   Contact  |   Syndication    |   Login
  199 Posts | 0 Stories | 1106 Comments | 51 Trackbacks


View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers

Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Post Categories



Recently we had a project where we needed to render certain questions on the screen dynamically based on answers to previous questions on previous screens.  For questions that need to dynamically be visible/invisible on the same screen, this can simply be controlled with jQuery.  However, in this case, based on the user’s input on previous screens we know there are certain questions that will not be applicable before the current screen even loads. In this case, we could use jQuery to set those questions invisible as well – but given we know the questions will not be applicable for this user, it would be more efficient to filter those questions out to start with which minimizes the HTML that is sent down to the browser. Additionally, the client wanted a way to easily map the question answers to the requirements. 

For this example, suppose that on a previous screen, the user indicated that they are married. On the current screen, some of the information that needs to be collected is information on the spouse – but this should only be part of the screen if the user indicated they were married on the previous screen. The original code from the view models looked something like this:

   1:  public bool ShouldShowNB0021FirstName { get; set; }
   2:  public string NB0021FirstName { get; set; }
   3:  public bool ShouldShowNB0022LastName { get; set; }
   4:  public string NB0022LastName { get; set; }
   5:  public bool ShouldShowNB0023Age { get; set; }
   6:  public int NB0023Age { get; set; }

A couple of things immediately jump out about this code. First, the property names are prefixed with a cryptic identifier (e.g., “NB0021”). This identifier is probably very meaningful to some business analyst somewhere and helps map back to the requirements doc but it’s somewhat distracting on the property names. Further, it’s going to render in the HTML mark up on the html element names which is a little odd. Also, each of these properties has a corresponding Boolean property which controls visibility for it. This resulted in views that looked somewhat like this:

   1:  <% if (this.Model.ShouldShowNB0021FirstName) {  %>
   2:      <div>
   3:          <%: Html.LabelFor(m => m.NB0021FirstName) %>
   4:          <%: Html.TextBoxFor(m => m.NB0021FirstName) %>
   5:      </div>
   6:  <% } %>
   7:  <% if (this.Model.ShouldShowNB0022LastName) {  %>
   8:      <div>
   9:          <%: Html.LabelFor(m => m.NB0022LastName) %>
  10:          <%: Html.TextBoxFor(m => m.NB0022LastName)%>
  11:      </div>
  12:  <% } %>
  13:  <% if (this.Model.ShouldShowNB0023Age) {  %>
  14:      <div>
  15:          <%: Html.LabelFor(m => m.NB0023Age) %>
  16:          <%: Html.TextBoxFor(m => m.NB0023Age)%>
  17:      </div>
  18:  <% } %>

While this certainly works, it’s a little verbose and not particularly DRY. Further, there is a lot of procedural code necessary to appropriately assign the Boolean visibility properties before rendering the view.

So let’s see how we can refactor this a little to save ourselves some work. First off, let’s create a custom attribute called “QuestionId” so that we can simplify the property names:

   1:  [QuestionId("NB0021")]
   2:  public string FirstName { get; set; }
   4:  [QuestionId("NB0022")]
   5:  public string LastName { get; set; }
   7:  [QuestionId("NB0023")]
   8:  public int Age { get; set; }

The implementation of the attribute is trivial:

   1:  public class QuestionIdAttribute : Attribute
   2:  {
   3:      public string Id { get; set; }
   5:      public QuestionIdAttribute(string id)
   6:      {
   7:          this.Id = id;
   8:      }
   9:  }

Next, let’s just add a single property to the view model (let’s call it “ApplicableQuestions”) which contains the collection of QuestionId’s that are still applicable given all the user’s answers on the previous screens. This “applicability logic” is encapsulated in another layer and beyond the scope of this post. What is relevant is that it will return an array of QuestionId’s that are still applicable. This now allows are views to look like this:

   1:  <% if (Model.ApplicableQuestions.Contains("NB0022")) { %>
   2:      <%: Html.EditorFor(m => m.LastName)%>
   3:  <% } %>

This is somewhat better because we don’t have to have all of the Boolean visibility properties, but I’ve still got a bunch of IF statement in the view and the identifier is still cryptic. To solve this, let’s created a custom EditorTemplate called “ScalarQuestion.ascx” that is meant for all questions that have basic text boxes. We can complete our view model by adding [UIHint] attributes as well as [DisplayName] attributes. Now the properties of our view model look like this:

   1:  [UIHint("ScalarQuestion")]
   2:  [DisplayName("First Name")]
   3:  [QuestionId("NB0021")]
   4:  public string FirstName { get; set; }
   6:  [UIHint("ScalarQuestion")]
   7:  [DisplayName("Last Name")]
   8:  [QuestionId("NB0022")]
   9:  public string LastName { get; set; }
  11:  [UIHint("ScalarQuestion")]
  12:  [QuestionId("NB0023")]
  13:  public int Age { get; set; }
  15:  public IEnumerable<string> ApplicableQuestions { get; set; }

Ultimately, we want to be able to call the EditorFor() method without having to wrap it in an IF statement which we can now do like this:

   1:  <%: Html.EditorFor(m => m.FirstName, new { applicableQuestions = Model.ApplicableQuestions })%>
   2:  <%: Html.EditorFor(m => m.LastName, new { applicableQuestions = Model.ApplicableQuestions })%>
   3:  <%: Html.EditorFor(m => m.Age, new { applicableQuestions = Model.ApplicableQuestions })%>

Since we’re passing in the list of applicable questions, the editor template can check to see if it should display:

   1:  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
   2:  <%@ Import Namespace="DynamicQuestions.Models" %>
   3:  <%@ Import Namespace="System.Linq" %>
   4:  <% 
   5:      var applicableQuestions = this.ViewData["applicableQuestions"] as IEnumerable<string>;
   6:      var questionAttr = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(QuestionIdAttribute), true) as QuestionIdAttribute[];
   7:      string questionId = null;
   8:      if (questionAttr.Length > 0)
   9:      {
  10:          questionId = questionAttr[0].Id;
  11:      }
  12:      if (questionId != null && applicableQuestions.Contains(questionId)) { %>
  13:          <div>
  14:              <%: Html.Label("") %>
  15:              <%: Html.TextBox("", this.Model)%>
  16:          </div>
  17:  <%  } %>

One line #5 we get the applicable question that were passed in. Then we check for the [QuestionId] attribute on the view model property – if it’s there, then we know we need to display the HTML – if not, we don’t. At this point we’ve 1) eliminated all of the Boolean visibility properties, 2) eliminated the cryptic identifier from the property name and made it part of metadata instead by using a declarative attribute, 3) eliminated all of the IF statements in the views, and 4) automatically mapped the applicability identifiers to the metadata specified on the view model. The only thing that still bugs me a little is the fact that having to create the anonymous type to pass the ApplicableQuestions property for every property means our code still violates DRY. To improve this, let’s create a custom Html helper called QuestionFor():

   1:  public static MvcHtmlString QuestionFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class, IApplicable
   2:  {
   3:      return htmlHelper.EditorFor(expression, new { applicableQuestions = htmlHelper.ViewData.Model.ApplicableQuestions });
   4:  }

Note that I introduced an interface called IApplicable which simply has a single property:

   1:  public interface IApplicable
   2:  {
   3:      IEnumerable<string> ApplicableQuestions { get; set; }
   4:  }

I can have my view models that have the ApplicableQuestions property implement this interface so that we can utilize the generic constraint on the HTML helper. Now my view becomes simplicity:

   1:  <%: Html.QuestionFor(m => m.FirstName) %>
   2:  <%: Html.QuestionFor(m => m.LastName) %>
   3:  <%: Html.QuestionFor(m => m.Age) %>

A final consideration to keep in mind is validation. Given that some properties of the view model won’t be present when the user saves the screen, validating a dynamic UI must be taken into account. The code sample for this post can be downloaded here.

posted on Wednesday, September 8, 2010 11:37 PM


# re: MVC 2 Model Metadata to Render Dynamic UI 9/15/2010 5:12 AM rtpHarry
This is an interesting post with some clever ideas to clean things up. You're obviously a skilled developer :)

# re: MVC 2 Model Metadata to Render Dynamic UI 9/17/2010 4:56 AM Jon
Clever stuff indeed, lots of techniques to steal there! Cheers.

# re: MVC 2 Model Metadata to Render Dynamic UI 9/17/2010 3:24 PM Thanigainathan
Thats an awsome article.


# re: MVC 2 Model Metadata to Render Dynamic UI 11/5/2010 8:48 AM Carson
Love this. One question, though:
How would you handle it, if your dynamic view model fields don't all use the same control (e.g., textbox)? I have dynamic fields that need a mixture of textboxes, date pickers, and integer spinners. They're already set up with [UIHint]s for their respective user controls.

Expanding each of the existing user controls with the 'do I display you?' logic (in your ScalarQuestion) seems like a mess.

Another thought would be adding another layer of if/thens in ScalarQuestion, and somehow pass in the type data...
either in yet another custom attribute (e.g., QuestionType) or maybe as part of the QuestionId string. Yuck.

Any other suggestions would be very welcome.

# re: MVC 2 Model Metadata to Render Dynamic UI 11/5/2010 8:57 AM Carson
Expanding QuestionIdAttribute to take an Id string and a type identifier, might cut down on the yuck factor. Still would need the if/thens in ScalarQuestion, though.

# re: MVC 2 Model Metadata to Render Dynamic UI 11/10/2010 8:14 AM Steve
@Carson - Another approach you might take is to lift the IF statement from the actual *.ascx code into the C# code of QuestionFor(). Because that QuestionFor() method internally calls html.EditorFor() then all your existing [UIHint] attributes will be honored.

Post A Comment