– SelectList returns as null in MVC DropDownList

I'm having problems using the Html.DropDownList helper on a MVC RC1 form.

In the controller class, I create a SelectList like this

SelectList selectList = new SelectList(db.SiteAreas, "AreaId", "AreaName");
ViewData["AreaId"] = selectList;

or like this

IEnumerable<SelectListItem> areaList =
    from area in db.SiteAreas
    select new SelectListItem
        Text = area.AreaName,
        Value = area.AreaId.ToString(),
        Selected = false
ViewData["AreaId"] = areaList;

and then add it into the viewer using this call

<% using (Html.BeginForm())
   { %>
   <label for="sitearea">Site Area:</label>
   <span class="hint">The menu option to be highlighted when the page is open </span>
   <br />
   <%= Html.DropDownList("sitearea", (SelectList)ViewData["AreaId"], "Select Area Id")%>
   <%= Html.ValidationMessage("sitearea") %>
   <br />
   <br />
   <input type="submit" value="Add New Page" />
   <% = Html.AntiForgeryToken() %>
<% } %>

So I'm adding a default option to the Dropdownlist as well. If I run this page and click the submit button without doing anything, I expected the POST action for this page to fire and for the validation code on this drop down list to tell me I haven't chosen an option.

Instead, (after attaching the MVC source code to my project), I find I'm getting an ArgumentNullException in selectextensions.cs.

$exception  {"Value cannot be null.\r\nParameter name: selectList"} System.Exception {System.ArgumentNullException}

This relates to a method called SelectInternal which is expecting a value other than null for its selectList parameter.

private static string SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, bool allowMultiple, IDictionary<string, object> htmlAttributes) 
   if (String.IsNullOrEmpty(name)) {
      throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
   if (selectList == null) {
      throw new ArgumentNullException("selectList");
.. rest of method ..

Now all I've done is upgrade the code from MVC beta 1 to RC1 and suddenly this has turned up. I've seen references to this SelectInternal method before, but no concrete resolution. So can anyone help me figure out why this error is occurring and how to fix it?

Thanks in advance

Best Solution

Figured it out, thanks to this link. It turns out that when the form is posted back to the server, validation actually is occuring on my controller but if validation fail, the controller tries to redisplay the form. However, the SelectLists have been set back to null somewhere along the line so I have had to recreate the SelectLists on that page as well.

I'm not sure if this is a bug in MVC or just a bug on my part, but for reference, there's the solution. Cheers.