2013-06-01 108 views
0

我想加載一個下拉列表從我的MySQL數據庫收到的值。ASP.NET MVC的下拉列表+保存selectedvalue

這是我在我的視圖模型

public int ProjectID { get; set; } 
public IEnumerable<SelectListItem> Projects { get; set; } 

在我控制器創建功能:

public ActionResult Create(DeliverableViewModel model) 
    { 
     var projects = (repository.GetProjects()).ToList(); 
     ViewBag.Projects = projects; 

     if (ModelState.IsValid) 
     { 
      try 
      { 

       repository.AddDeliverable(model.ProjectID); 
      } 
      catch (ArgumentException ae) 
      { 
       ModelState.AddModelError("", ae.Message); 
      } 
      return RedirectToAction("Index"); 
     } 

     return View(model); 
    } 

我加載項目在我的倉庫。 (值:PROJECT_ID和PROJECT_NAME)

這是我創建查看

@model GDMfrontEnd.Models.DeliverableViewModel 

@{ 
    ViewBag.Title = "Create"; 
} 

<h2>Create</h2> 

    @using (Html.BeginForm("Create", "Deliverable", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
     @Html.ValidationSummary(true) 

      <div class="editor-field"> 
       @Html.DropDownListFor(model => model.Projects, 
     new SelectList(ViewBag.Projects, 
     "project_id", "project_name")) 
      </div> 
      <p> 
       <input type="submit" value="Create" /> 
      </p> 

    } 

但現在,我怎麼給我的專案編號從選定值我的倉庫?

回答

4

假設:

class DeliverableViewModel 
{ 
    public int ProjectID { get; set; } 
    public IEnumerable<SelectListItem> Projects { get; set; } 
} 

它應該是這樣的:

@Html.DropDownListFor(model => model.ProjectID, 
    new SelectList(Model.Projects, "project_id", "project_name", Model.ProjectID)) 

可以省略最後Model.ProjectID如果你不初始化這個領域,但你可能會使用它編輯。

+0

謝謝!它非常完美! – nielsv

0

它應該是model=>model.ProjectID在POST操作中檢索選定的ProjectID。

@Html.DropDownListFor(model => model.ProjectID, 
      new SelectList(ViewBag.Projects, 
      "project_id", "project_name"))