Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This appears to be a bug in the SelectExtensions class as it will only check the ViewData rather than the model for the selected item. So the trick is to copy the selected item from the model into the ViewData collection under the name of the property.</p> <p>This is taken from the answer I gave on the MVC forums, I also have a more complete answer in a <a href="http://blog.paulhatcher.com/archive/2010/06/28/mvc-2-editorformodel-and-dropdownlist.aspx" rel="nofollow noreferrer">blog post</a> that uses <a href="http://weblogs.asp.net/rashid/archive/2010/02/09/asp-net-mvc-complex-object-modelmetadata-issue.aspx" rel="nofollow noreferrer" title="Kazi&#39;s attribute">Kazi's DropDownList attribute</a>... </p> <p>Given a model</p> <pre><code>public class ArticleType { public Guid Id { get; set; } public string Description { get; set; } } public class Article { public Guid Id { get; set; } public string Name { get; set; } public ArticleType { get; set; } } </code></pre> <p>and a basic view model of </p> <pre><code>public class ArticleModel { public Guid Id { get; set; } public string Name { get; set; } [UIHint("DropDownList")] public Guid ArticleType { get; set; } } </code></pre> <p>Then we write a DropDownList editor template as follows..</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt; &lt;script runat="server"&gt; IEnumerable&lt;SelectListItem&gt; GetSelectList() { var metaData = ViewData.ModelMetadata; if (metaData == null) { return null; } var selected = Model is SelectListItem ? ((SelectListItem) Model).Value : Model.ToString(); ViewData[metaData.PropertyName] = selected; var key = metaData.PropertyName + "List"; return (IEnumerable&lt;SelectListItem&gt;)ViewData[key]; } &lt;/script&gt; &lt;%= Html.DropDownList(null, GetSelectList()) %&gt; </code></pre> <p>This will also work if you change ArticleType in the view model to a SelectListItem, though you do have to implement a type converter as per Kazi's blog and register it to force the binder to treat this as a simple type. </p> <p>In your controller we then have...</p> <pre><code>public ArticleController { ... public ActionResult Edit(int id) { var entity = repository.FindOne&lt;Article&gt;(id); var model = builder.Convert&lt;ArticleModel&gt;(entity); var types = repository.FindAll&lt;ArticleTypes&gt;(); ViewData["ArticleTypeList"] = builder.Convert&lt;SelectListItem&gt;(types); return VIew(model); } ... } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload