我剛做了一個包含DropDownList的表單,它完美地顯示了選項名稱,但不會將所選選項的ID發佈到控制器中。C#MVC3 DropDownList - 在表單中找不到ID
這裏是控制器代碼:
[HttpGet]
public ActionResult Insert(int id)
{
TemplateRepository repo = new TemplateRepository();
List<Template> templateList = repo.ListAll().ToList<Template>();
ViewData["Template"] = new SelectList(templateList, "Id", "Omschrijving");
return View();
}
[HttpPost]
public ActionResult InsertOrEditSubmit(Klant klant)
{
KlantRepository repo = new KlantRepository();
klant.Naam = Request["Naam"];
klant.Adres = Request["Adres"];
klant.Postcode = Request["Postcode"];
klant.Woonplaats = Request["Woonplaats"];
klant.Email = Request["Email"];
klant.Telefoon = Request["Telefoon"];
repo.SaveOrUpdate(klant);
return RedirectToAction("Index");
}
這裏是在視圖代碼:
@using (Html.BeginForm("InsertOrEditSubmit", "Klant", FormMethod.Post))
{
@Html.DevExpress().Label(
settings =>
{
settings.ControlStyle.CssClass = "label";
settings.Text = "Template";
settings.AssociatedControlName = "Template";
}
).GetHtml() <br />
@Html.DropDownList("Template", ViewData["Template"] as SelectList);
@Html.DevExpress().Button(
settings =>
{
settings.ControlStyle.CssClass = "button";
settings.Name = "Insert";
settings.Text = "Toevoegen";
settings.UseSubmitBehavior = true;
}
).GetHtml()
@Html.DevExpress().Button(
settings =>
{
settings.ControlStyle.CssClass = "button";
settings.Name = "Cancel";
settings.Text = "Terug";
settings.ClientSideEvents.Click = "function(s, e){ document.location='" + DevExpressHelper.GetUrl(new { Controller = "Gebruiker", Action = "Index" }) + "'; }";
}
).GetHtml()
}
希望有人可以解釋爲什麼它不發佈ID ..
如果我嘗試請求[「Template」];它給了我錯誤:不能隱式地將類型'字符串'轉換爲'DomainClasses.Domain.Template'。 – Smoothal 2012-04-18 10:51:37
在控制器中,我使用quickview檢查發佈的數據,並將「Template」處的值定義爲null。 – Smoothal 2012-04-18 10:58:06
您確定您的「templateList」具有名爲「Id」的字段嗎? – artisonus 2012-04-18 11:24:26