ASP.Net MVC 2 DropDownListFor in EditorTemplate

Posted by tschreck on Stack Overflow See other posts from Stack Overflow or by tschreck
Published on 2010-04-22T18:49:40Z Indexed on 2010/04/22 20:23 UTC
Read the original article Hit count: 5250

I have a view model that looks like this:

namespace AutoForm.Models
{
    public class ProductViewModel
    {
        [UIHint("DropDownList")]
        public String Category { get; set; }

        [ScaffoldColumn(false)]
        public IEnumerable<SelectListItem> CategoryList { get; set; }

        ...
    }
}

It has Category and CategoryList properties. The CategoryList is the source data for the Category dropdown UI element.

I have an EditorTemplate that looks like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ProductViewModel>" %>
<%@ Import Namespace="AutoForm.Models"%>

<%=Html.DropDownListFor(m => m.Category , Model.CategoryList ) %>

NOTE: this EditorTemplate is strongly typed to ProductViewModel

My Controller is populating CategoryList property with data from a database.

I cannot get the DropDownListFor template to render a drop down list with data from CategoryList. I know CategoryList is getting populated with data in the controller because I see the data when I debug and step through the controller.

Here's my error message in the browser:

Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 2: <%@ Import Namespace="AutoForm.Models"%> Line 3: Line 4: <%=Html.DropDownListFor(m => m.Category, Model.CategoryList) %>

Source File: c:\ProjectStore\AutoForm\AutoForm\Views\Shared\EditorTemplates\DropDownList.ascx Line: 4

Any ideas?

Thanks

Tom


As a followup, I noticed that ViewData.Model is null when I'm stepping through the code in the EditorTemplate. I have the EditorTemplate strongly typed to "ProductViewModel" which is also the type that's passed to the View in the controller. I'm perplexed as to why ViewData.Model is null even though it's getting populated in the controller before getting passed to the view.

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about editortemplates