Search code examples
c#asp.net-mvcrazor

Object reference not set to an instance of an object. Model.country is returning null


@Html.DropDownListFor(model => Model.country, Model.country)
public class Registration
{
    public List<SelectListItem> country { get; set; }

    public Registration()
    {            
        country = new List<SelectListItem>
        {
            new SelectListItem { Value = "1", Text = "India" },
            new SelectListItem { Value = "2", Text = "USA" },
            new SelectListItem { Value = "3", Text = "UK" },            
        };
    }
}

I am trying to populate the country in DropDownList in view but I am get error. It is returning Model.country is null. Country list is not bound to country.


Solution

  • Try the following example.

    The Index action method:

    public ActionResult Index()
    {
        var model = new Registration()
        {
            country = new List<SelectListItem>
            {
                new SelectListItem { Value = "1", Text = "India" },
                new SelectListItem { Value = "2", Text = "USA" },
                new SelectListItem { Value = "3", Text = "UK" },
            }
        };
        return View(model);
    }
    

    The Index.cshtml markup:

    @model Models.Registration
    <div class="form-group">
        @Html.DropDownListFor(m => Model.country.GetEnumerator().Current, Model.country, "-select a value-")
    </div>
    

    I suppose you have an error in the view code that you don't included to the question.