MVC DropDownListFor - "Object reference not set to instance of object"

916 views Asked by At

I'm getting a null reference error with my dropdownlistfor in my partial view. I can't seem to find what I'm missing or doing wrong to get an empty object reference. ModelCode:

CommonHerpNames.cs

public class CommonHerpNames
    {
        [Key]
        public int CommonHerpId { get; set; }

        public string HerpName { get; set; }
}

NewReptileViewModel.cs

public class NewReptileViewModel
{
    public IEnumerable<CommonHerpNames> CommonAnimalNames { get; set; }
    public ReptileModel ReptileModel { get; set; }
}

Controller Code:

  public ActionResult _AddReptile()
    {
        var commonAnimalTypes = _context.CommonHerps.ToList();
        var viewModel = new NewReptileViewModel
        {
           CommonAnimalNames = commonAnimalTypes
        };            

        return PartialView("_AddReptile", viewModel);
    }

Partial ViewCode:

<div class="form-group">
     @Html.DropDownListFor(model => model.ReptileModel.CommonHerpTypeId, new SelectList(Model.CommonAnimalNames, "CommonHerpId", "HerpName"), "Select Animal")
</div>

Main View Code:

<div>
    @Html.Partial("_addReptiles")
</div>

For the record, I know my CommonHerps context is good as I recently completed an Add-Migration and Update-Database -Verbose.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Using Html.Partial() does not call your server method. It just renders the partial view (passing the model in the main view to the partial) and the error is thrown because CommonAnimalNames is null and you cannot initialize a new SelectList for a null.

Change the code in the main view to

@Html.Action("_AddReptile") // add controller name as 2nd parameter if necessary

or

@{ Html.RenderAction("_AddReptile"); }

which will call your _AddReptile() method, which will in turn initialize your view model and set the value of CommonAnimalNames.

You may also want to consider marking _AddReptile() with the [ChildActionOnly] attribute to prevent it being called by the browser.