2015-06-17 75 views
1

我的視圖模型是這樣的:DropDownListFor總是返回null到控制器

public class ProjectViewModel 
    { 
     public ICollection<Project> Projects { get; set; } 
    } 

我的控制器:

[HttpPost] 
    [Route("ChooseProject")] 
    public ActionResult ChooseProject(Project projects) 
    { 
     return RedirectToAction("Index", "Application"); 
    } 

最後我的看法:

@using ServicePortal.Web.Controllers 
@model ServicePortal.Web.Models.ProjectViewModel 
@{ 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
    ViewBag.Title = "Choose project"; 
} 

<div class="pure-form pure-form-aligned"> 
    @using (Html.BeginForm("ChooseProject", "Login", FormMethod.Post)) 
    { 
     @Html.AntiForgeryToken() 
     <div class="innerForm formgroup"> 
      @Html.ValidationSummary(true, "", new { @class = "" }) 

      @Html.DropDownListFor((model => model.Projects), new SelectList(Model.Projects,"ProjectKey", "ProjectName")) 

      <div class="row"> 
       <button type="submit" class="button pull-right">Go on</button>, 
      </div> 
     </div> 
    } 
</div> 

的下拉列表填充了正確的值,但我想返回一個項目或帶有ProjectKey的字符串到控制器。但是,當我提交表單並檢查控制器中參數的值時,它始終爲空,無論是在嘗試返回項目還是嘗試使用字符串時。我沒有得到任何錯誤。我究竟做錯了什麼?

回答

2

嘗試了這一點:

public class ProjectViewModel 
{ 
    public string SelectedProjectKey { get; set; } // string may need to be int depending on what type ProjectKey is in your class 
    public ICollection<Project> Projects { get; set; } 
} 

在視圖:

@Html.DropDownListFor((model => model.SelectedProjectKey), new SelectList(Model.Projects,"ProjectKey", "ProjectName")) 

你的控制器動作:

public ActionResult ChooseProject(ProjectViewModel model) 

這將讓你你在模型中選擇任何項目的關鍵.SelectedProjectKey,你可以在你的控制器選擇項目動作方法中使用它來做你想做的事情。