I have created a partial view that displays a dropdownlist
html.DropDownListFor(m => m.SelectOption, Model.SelectOption)
I get an error of Object not reference to an instance....
If I put the code above into my view (aspx) it works fine no problem. But in the partial view I get the error.
The textbox controls in my partial view works fine using the same model. I just can't around the DropDownList.
You haven't actually shown how you are calling the partial view and whether your controller action has actually passed a model to this view.
Make sure that your controller has properly initialized the model. So if we suppose that you have the following model:
public class MyViewModel
{
public string SelectedOption { get; set; }
public IEnumerable<SelectListItem> SelectOptions { get; set; }
}
and the following controller action:
public ActionResult Foo()
{
var model = new MyViewModel();
model.SelectOptions = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
return View(model);
}
ten you could have a corresponding view which will call a partial:
@model MyViewModel
@Html.Partial("_MyPartial", Model)
and the _MyPartial.cshtml
:
@model MyViewModel
@Html.DropDownListFor(x => x.SelectedOption, Model.SelectOptionOptions)
Notice how you need 2 properties on your view model in order to create a dropdown list => a scalar property (SelectedOption
) that will be used to bind the selected value and a collection property that will contain the list of values you would like to display in the dropdown (SelectOptionOptions
).
In your code you are using the same property for both which is wrong:
@Html.DropDownListFor(m => m.SelectOption, Model.SelectOption)