Skip to content

Instantly share code, notes, and snippets.

@darrencauthon
Created January 11, 2012 13:02
Show Gist options
  • Save darrencauthon/1594558 to your computer and use it in GitHub Desktop.
Save darrencauthon/1594558 to your computer and use it in GitHub Desktop.
Dropdowns in ASP.Net MVC (with MVC Turbine)
<% Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Linq" %>
<%
var items = ViewData.ModelMetadata.AdditionalValues["SelectList"] as IList<SelectListItem>;
<select id="<%=ViewData.ModelMetadata.PropertyName %>" name="<%=ViewData.ModelMetadata.PropertyName %>" <%=(ViewData.ModelState.ContainsKey(ViewData.ModelMetadata.PropertyName) && ViewData.ModelState[ViewData.ModelMetadata.PropertyName].Errors.Any()) ? "class=\"input-validation-error\"" : string.Empty %>>
<%foreach (var item in items)
{%>
<option value="<%=HttpUtility.HtmlEncode(item.Value)%>" <%=item.Value == ViewData.Model.ToNullSafeString() ? " selected" : ""%>>
<%=Html.Encode(item.Text)%></option>
<%}%>
</select>
public abstract class DropdownListAttributeHandler<T> : IMetadataAttributeHandler<T>
{
public abstract IList<SelectListItem> GetItems();
public virtual void AlterMetadata(ModelMetadata metadata, CreateMetadataArguments args)
{
metadata.TemplateHint = "DropDownList";
metadata.AdditionalValues["SelectList"] = GetItems();
}
}
<%: Html.EditorFor(x=>x.Street) %>
<%: Html.EditorFor(x=>x.Street2) %>
<%: Html.EditorFor(x=>x.City) %>
<%: Html.EditorFor(x=>x.State) %>
<%: Html.EditorFor(x=>x.Zip) %>
public class SampleInputModel{
public string Street { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
[StateDropdown]
public string State { get; set; }
public string Zip { get; set; }
}
public class StateDropdownAttribute : MetadataAttribute {}
public class StateDropdownAttributeHandler : DropdownListAttributeHandler<StateDropdownAttribute>
{
public override IEnumerable<SelectListItem> GetItems()
{
return new[]
{
new SelectListItem {Text = "Kansas", Value = "KS"},
new SelectListItem {Text = "Missouri", Value = "MO"}
};
}
}
@darrencauthon
Copy link
Author

Things to note:

1.) All dropdowns share the same editor template, so if you want to change how dropdowns are rendered you do it in one place and you do it in HTML.

2.) Marking a property on an input model can switch a property from being rendered with the default editor template for that type (string, int, etc) to using an editor template like "DropdownList."

3.) The data used to populate the dropdown is tucked away in metadata and the "handler" class for the attribute. This means that it stays out of the controller and out of the editor template (SampleInputModel.aspx).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment