我无法从下拉菜单中将所选值返回给控制器。我在网上搜索,但找不到任何内容(可能是我在找错东西的错误)
我希望我给了您解决我的问题所需的代码。如果您解释原因,那也很好,因为我想从我的过失中学习一些东西。
我的班级菜单:
public class Menu
{
public int Id { get; set; }
[Required]
public string Naam { get; set; }
[Required]
public decimal Prijs { get; set; }
public Gerecht Voorgerecht { get; set; }
public Gerecht Hoofdgerecht { get; set; }
public Gerecht Nagerecht { get; set; }
}
我的班子Gerecht:
public class Gerecht
{
public int Id { get; set; }
[Required]
public string Naam { get; set; }
}
我的模型视图:
public class MenuViewModel
{
public int Id { get; set; }
[Required]
public string Naam { get; set; }
[Required]
public decimal Prijs { get; set; }
public IEnumerable<Gerecht> Voorgerecht;
public IEnumerable<Gerecht> Hoofdgerecht;
public IEnumerable<Gerecht> Nagerecht;
}
我的Createhtml:
<div class="form-group">
@Html.LabelFor(model => model.Voorgerecht, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Voorgerecht, new SelectList(Model.Voorgerecht, "Id", "Naam"), "Select a product")
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Hoofdgerecht, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Hoofdgerecht, new SelectList(Model.Hoofdgerecht, "Id", "Naam"), "Select a product")
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Nagerecht, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Nagerecht, new SelectList(Model.Nagerecht, "Id", "Naam"), "Select a product")
</div>
</div>
我的控制器:
// GET: Menus/Create
public ActionResult Create()
{
var menuViewModel = new MenuViewModel();
menuViewModel.Voorgerecht = db.Gerechts.ToList();
menuViewModel.Hoofdgerecht = db.Gerechts.ToList();
menuViewModel.Nagerecht = db.Gerechts.ToList();
return View(menuViewModel);
}
// POST: Menus/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Naam,Prijs")] MenuViewModel menu)
{
if (ModelState.IsValid)
{
Gerechten gerecht = new Gerechten();
Menu menutjes = new Menu();
menutjes.Id = menu.Id;
menutjes.Naam = menu.Naam;
menutjes.Prijs = menu.Prijs;
//gerecht = menu.Voorgerecht;
//menutjes.Voorgerecht = menu.Voorgerecht.;
//menutjes.Hoofdgerecht = menu.Hoofdgerecht;
//menutjes.Nagerecht = menu.Nagerecht;
db.Menus.Add(menutjes);
db.SaveChanges();
return RedirectToAction("Index");
}
var menuViewModel = new MenuViewModel();
menuViewModel.Voorgerecht = db.Gerechts.ToList();
menuViewModel.Hoofdgerecht = db.Gerechts.ToList();
menuViewModel.Nagerecht = db.Gerechts.ToList();
return View(menuViewModel);
}