I'm having so much problems for this basic thing in regards to dropdownlist I did so many methods described in stackoverflow and all didn't work I will sum the code like this. I just want to simple create a dropdownlist that is saved to the database.
Here is what I did DefaultModel
public class DefaultModel
{
public int Id {get; set;}
//other things
public CountryList SelectedCountry {get; set;}
}
public DefaultDbContext : DbContext
{
public DbSet<DefaultModel> DefaultModels {get; set;}
public DbSet<CountrtyList> CountryLists {get; set;}
}
CountryList Model
public class CountryList
{
public byte Id {get; set;}
public string name {get; set;} //country name
public DefaultModel DefaultModel {get; set;}
}
ViewModel
public class CountryListViewModel
{
public byte Id {get; set;}
public List<CountryList> CountryList {get; set;}
DefaultController Not Home Controller
private DefaultDbContext = db;
public HomeController
{
db = new DefaultDbContext;
}
public ActionResult Index()
{
var countryLists= _context.CountryLists.ToList();
var viewModel = new CountryListViewModel
{
Default = new DefaultModel(),
CountryLists = countrylists
};
return View(viewModel);
}
View
@model Default.ViewModels.CountryListViewModel
<div class="form-group">
@Html.LabelFor(model =>
model.TransactionModel.SelectedCountry.CountryLists
, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(
model => model.TransactionModel.SelectedCountry.CountryLists
, new SelectList(Model.CountryList, "Id, Name"), "Select Country")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
Migration adding Countries
Sql("INSERT INTO COUNTRYLISTS (Id, Name) VALUES(1, UK)");
Error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I'm just trying to learn how to create a dropdownlist in MVC5 from scratch and I wasted allot of hours & constantly failing at multiple attempts. I see tutorials that use ways that simply don't work I have no idea what is wrong or what I should do.