This is the error im getting, I am getting the value that the droplist is sending, but when it try to add it to the data it just crashes and im getting the error that i wrote abow.
I have tried updating the html tag to
@Html.DropDownList("WorkStations", (SelectList)ViewBag.WorkStations)
This is my model
namespace MvCfirstproject.Models
{
[Table("WorkHoursModels")]
public class WorkhoursModels
{
public int Id { get; set; }
public string Start { get; set; }
public string Stop { get; set; }
public string command { get; set; }
public string Users { get; set; }
public string WorkStations { get; set; }
}
[Table("WorkStations")]
public class WorkHoursStation
{
public int Id { get; set; }
public string WorkStations { get; set; }
public IEnumerable<SelectListItem> Workstations { get; set; }
}
public class WorkhourDB : DbContext
{
public DbSet<WorkhoursModels> WorkHours { get; set; }
public DbSet<WorkHoursStation> WorkStation { get; set; }
}
}
This is my Controller
public ActionResult Create()
{
ViewBag.WorkStations = new SelectList(db.WorkStation, "WorkStations", "Workstations");
return View();
}
//
// POST: /Default1/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(WorkhoursModels workhoursmodels)
{
if (workhoursmodels.command == "Users")
{
db.WorkHours.Add(workhoursmodels);
db.SaveChanges();
}
}
And this is my view
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.Users)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Users)
@Html.ValidationMessageFor(model => model.Users)
</div>
<div>
@Html.DropDownList("WorkStations", String.Empty)
</div>
<p>
<input type="submit" name="@Html.NameFor(x => x.command)" value="User"/>
</p>
}
Assuming that you're view is strongly typed for the model WorkhoursModels
You don't need a viewbag because you're defining a IEnumerable in the properties of your model just change the Action passing the model to the view
public ActionResult Create()
{
WorkhoursModels model = new WorkhoursModels();
model.Workstations = db.WorkStation.Select(x => new SelectListItem() { Text = x.WorkStations , Value = x.Id.ToString() });
return View(model);
}
Use the properly helper
@Html.DropDownListFor(model => model.Id, Model.Workstations, string.Empty)