4

I can't find the answer why I'm getting NullReferenceException when I'm trying to use DropDownListFor() like this:

View:

<div class="form-group">
    @Html.LabelFor(m => m.Category, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownListFor(
            m => m.Category,
            new SelectList(Model.CategoryOptionsList, "CategoryOptionId", "Value", Model.CategoryOptionsList.First().CategoryOptionId),
            new { @class = "form-control" }
            )
    </div>
</div>

ViewModel:

public class CategoryOption 
{
    public int CategoryOptionId { get; set; }
    public string Value { get; set; }
}

public IEnumerable<CategoryOption> CategoryOptionsList = new List<CategoryOption> 
{
    new CategoryOption { CategoryOptionId = 0, Value="Rock" },
    new CategoryOption { CategoryOptionId = 1, Value="Jazz" },
    new CategoryOption { CategoryOptionId = 2, Value="Pop" },
    new CategoryOption { CategoryOptionId = 3, Value="Metal" },
    new CategoryOption { CategoryOptionId = 4, Value="Folk" }
};

[Required]
[Display(Name = "Kategoria")]
public string Category { get; set; }
abatishchev
  • 92,232
  • 78
  • 284
  • 421
magos
  • 2,997
  • 3
  • 23
  • 49
  • did you set your ViewModel ? and did you pass your model to the View when you returning it from controller? – Selman Genç Feb 12 '14 at 22:03
  • What line throws the error? We aren't mind readers. – Simon Whitehead Feb 12 '14 at 22:03
  • Selman22 - yes, i've passed like this: '@model IdentityTesting.Models.RegisterViewModel' SimonWhitehead '@Html.DropDownListFor( m => m.Category, //this line throws error. new SelectList(Model.CategoryOptionsList, "CategoryOptionId", "Value", Model.CategoryOptionsList.First().CategoryOptionId), new { @class = "form-control" } )' – magos Feb 12 '14 at 22:16
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – John Saunders Feb 12 '14 at 23:01
  • @magos: `@model IdentityTesting.Models.RegisterViewModel` only tells the view what the expected **type** of the model is. It doesn't actually **make** an object and pass it to the view. That's what your controller is supposed to do. – Flater Apr 23 '14 at 11:07

1 Answers1

18

I think you forgot to pass your ViewModel object to your view, see below:

public ActionResult YourAction()
{
    return View(new YourViewModel());
}
abatishchev
  • 92,232
  • 78
  • 284
  • 421
Lin
  • 14,568
  • 4
  • 45
  • 49