In my ASP.NET MVC 4 application, I have a .dbml file (Model) created via LINQ to SQL. And I have:
Controller Action
public ActionResult Index()
{
MyDataContext db = new MyDataContext();
ViewBag.Countries = db.Countries.ToList();
return View();
}
View
@model myProject.Models.Countries
<div>
@Html.DropDownListFor(m => m.CountryID, new SelectList(ViewBag.Countries, "CountryID", "CountryName"), "Select Country", new { id = "ddlCountries" })
</div>
The above dropdown list displays correctly with the names of the countries with the value as CountryID and the text as the Country name as follows:
Afghanistan
Albania
Algeria
...
...
Zambia
Zimbabwe
The database table Countries has other columns namely, "Capital" and "Population". I want to create custom data-attributes in the DropDownListFor for these two columns so that I can store data from the model in these columns and use that data in the textboxes for the Capital and the Population when a user selects a country in the dropdown. So, I modified the above view as follows:
@model myProject.Models.Countries
<div>
@Html.DropDownListFor(m => m.CountryID, new SelectList(ViewBag.Countries, "CountryID", "CountryName"), "Select CountryI", new { id = "ddlCountries", data_capital = Model.Capital, data_population = Model.Population })
</div>
In Visual Studio 2012, the intellisense recognizes the Model.Capital and Model.Population. But in the browser, veiw gives the following error at the line where the above dropdown is created:
System.NullReferenceException: Object reference not set to an instance of an object.
The Countries table has no null values. It seems I cannot add the custom data-attributes to the SelectList. Moreover, the data_capital and data_population in the above view are in fact added to the select element - not to the option element. So what is a workaround?
Please help.
Thanks..Nam