I am trying to save my dropdown list values to my database in an ASP.NET web application using MVC6 and Entity Framework 7 but the values are not saving.
I have two classes one called expenses and when a user creates an expense they need to select a country. I have the country dropdown list populating but when the expense is saved the countryid is not being saved to the database.
Models
public class Country
{ public int Countryid { get; set; }
public string CountryCode { get; set; }
}
public class Expense
{
public int ExpenseId { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime ExpenseDate { get; set; }
public virtual Country Countryid { get; set; }
Expense Controller
private void PopulateCountriesDropDownList(object selectedCountry = null)
{
var list = _context.Countries.OrderBy(r => r.CountryCode).ToList().Select(rr =>
new SelectListItem { Value = rr.Countryid.ToString(), Text = rr.CountryCode }).ToList();
ViewBag.Countries = list;
}
// GET: Expenses/Create
public IActionResult Create()
{
PopulateCountriesDropDownList();
return View();
}
// POST: Expenses/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Expense expense)
{
if (ModelState.IsValid)
{
_context.Expenses.Add(expense);
_context.SaveChanges();
return RedirectToAction("Index");
}
PopulateCountriesDropDownList(expense.Countryid);
return View(expense);
}
View
<div class="form-group">
<label asp-for="Countryid" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Countryid" class="form-control"[email protected]></select>
<span asp-validation-for="Countryid" class="text-danger" />
</div>
</div>