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.
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 becauseCommonAnimalNamesisnulland you cannot initialize a newSelectListfor anull.Change the code in the main view to
or
which will call your
_AddReptile()method, which will in turn initialize your view model and set the value ofCommonAnimalNames.You may also want to consider marking
_AddReptile()with the[ChildActionOnly]attribute to prevent it being called by the browser.