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; }
5
  • did you set your ViewModel ? and did you pass your model to the View when you returning it from controller? Commented Feb 12, 2014 at 22:03
  • What line throws the error? We aren't mind readers. Commented Feb 12, 2014 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" } )' Commented Feb 12, 2014 at 22:16
  • possible duplicate of What is a NullReferenceException and how do I fix it? Commented Feb 12, 2014 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. Commented Apr 23, 2014 at 11:07

1 Answer 1

18

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

public ActionResult YourAction()
{
    return View(new YourViewModel());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.