Start by fixing your model to match your database:
public class Tickets
{
public string Priorities { get; set; }
public string Categories { get; set; }
public string Site_Admins { get; set; }
...
NB: There's no need for the database columns to be
nvarchar(max)
- you're only going to be storing a single value in each field. If you want multiple values in each field, then your database structure is wrong, and you can't use a drop-down list. :)
You'll need to re-populate the lists in the
ViewData
if the posted model is not valid, so it's probably worth pulling that out into another method:
private void PopulateLists(Tickets model)
{
ViewData["Categories"] = new SelectList(_db.Categories, "Id", "CategoryName", model.Categories);
ViewData["Priorities"] = new SelectList(_db.Priorities, "Id", "PriorityName", model.Priorities);
ViewData["Site_Admins"] = new SelectList(_db.Site_Admins, "Id", "Name", model.Site_Admins);
}
public ActionResult Create()
{
var model = new Tickets();
PopulateLists(model);
return View(model);
}
public ActionResult Create(Tickets model)
{
if (!ModelState.IsValid)
{
PopulateLists(model);
return View(model);
}
_db.Tickets.Add(model);
_db.SaveChanges();
return RedirectToAction("Tickets");
}
NB: I just noticed the
SaveChangesAsync
call. You either need to use the synchronous
SaveChanges
method, or make your action
async
and
await
the results:
public async Task<ActionResult> Create(Tickets model)
{
if (!ModelState.IsValid)
{
PopulateLists(model);
return View(model);
}
_db.Tickets.Add(model);
await _db.SaveChangesAsync();
return RedirectToAction("Tickets");
}
In your view, make sure you have the correct class specified in the
@model
directive, and then use the
DropDownListFor
helper:
@Html.DropDownListFor(m => m.Site_Admins, (SelectList)ViewState["Site_Admins"], "Assign To", new { @class = "form-control" })
@Html.DropDownListFor(m => m.Priorities, (SelectList)ViewData["Priorities"], "Select Priority", new { @class = "form-control" })
@Html.DropDownListFor(m => m.Categories, (SelectList)ViewData["Categories"], "Select Category", new { @class = "form-control" })
This will generate three
<select>
elements with the correct name and ID, which will allow the model binder to match the posted value to the property on the model.