2012-06-14 89 views
0

我想要得到一個下拉列表來發送它在HTTP POST上的選擇以及其他相關數據。我可以看到表單集合中的值,但是當我查看其他發佈的實體時,VS2010告訴我該對象爲NULL。在模型對象中返回NULL的MVC3下拉列表

這種模式有一個多對一的關係:

[Key] 
public int ProgramTypeId { get; set; } 

public string ProgramType { get; set; } 

public List<SurveyProgramModels> SurveyProgramModel { get; set; } 

這款機型採用了ProgramTypeId作爲外鍵

public class SurveyProgramModels 
    { 
     [Key] 
     public Guid ProgramId { get; set; } 

     public virtual SurveyProgramTypeModels SurveyProgramTypeModels { get; set; } 

     public int ProgramYear { get; set; } 

     public int ProgramStatus { get; set; } 

    } 

控制器GET/POST

// 
     // GET: /SurveyProgram/Create 

     public ActionResult Create() 
     { 

      SelectList typelist = new SelectList(db.SurveyProgramTypeModels.ToList(), "ProgramTypeId", "ProgramType", db.SurveyProgramTypeModels); 
      ViewData["SurveyProgramTypeModels"] = typelist; 

      return View(); 
     } 

     // 
     // POST: /SurveyProgram/Create 

     [HttpPost] 
     public ActionResult Create(SurveyProgramModels surveyprogram, FormCollection collection) 
     { 


      SelectList typelist = new SelectList(db.SurveyProgramTypeModels.ToList(), "ProgramTypeId", "ProgramType", db.SurveyProgramTypeModels); 
      ViewData["SurveyProgramTypeModels"] = typelist; 

      // int SelectedCollection = Int32.Parse(collection["ProgramTypeId"]); 

      if (ModelState.IsValid) 
      { 
       surveyprogram.ProgramId = Guid.NewGuid(); 

       db.SurveyPrograms.Add(surveyprogram); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 

      return View(surveyprogram); 
     } 

選擇列表查看:

<div class="editor-field"> 
      @Html.DropDownList("ProgramTypeTypeModels", (IEnumerable<SelectListItem>)ViewData["SurveyProgramTypeModels"]) 
      @Html.ValidationMessageFor(model => model.SurveyProgramTypeModels) 
     </div> 

選擇列表在視圖中呈現時是正確的,我可以將選定值看作表單集合的一部分。我不確定爲什麼選定的值未與SurveyProgramModels的其他數據一起保存。

編輯:當我刪除兩個類之間的關係時,我還應該提及數據提交正確。

回答

2

表單元素被命名爲「ProgramTypeTypeModels」,這會導致它不能正確地綁定回去。您還應該創建一個Model以返回到View

然後包括SelectList作爲View

Model屬性現在你做這樣的事情:

@Html.DropDownListFor(model => model.SurveyProgramTypeModels) 

而對於[HttpPost],那麼你可以採取的強類型Model作爲參數, aspnet綁定將完成所有的工作,沒有理由讓DTO脫離FormCollection