Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException in use DropDownListFor in ASP.NET MVC 5

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; }
like image 714
magos Avatar asked Dec 02 '22 17:12

magos


1 Answers

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

public ActionResult YourAction()
{
    return View(new YourViewModel());
}
like image 136
Lin Avatar answered Dec 04 '22 05:12

Lin