2012-02-06 72 views
0

结合我不知道为什么下拉列表中没有这种特殊情况下的工作:DropDownListFor不与模型属性

我知道,我已经专案编号> 0,但在下拉列表我总是看到第一个项目选择。

控制器:

Helpers h = new Helpers(); 

[HttpGet] 
[ActionName("Timesheet")] 
public ActionResult TimeSheet(LoggedAssociate assoc, DateChooserModel model) 
{    
    List<TimeReport> timeReports = db.TimeReports.Include("TimeEntries.Project").Where(
     tr => tr.AssociateID == assoc.ID && 
     tr.DateSubmitted >= model.StartDate && 
     tr.DateSubmitted <= model.FinishDate).ToList(); 

    ViewBag.Projects = h.GetProjects(0); 

    return View(timeReports); 
}  

助手:

public class Helpers 
{ 
    public MyRepository db = new MyRepository(); 

    public IEnumerable<SelectListItem> GetProjects(short? selectedValue) 
    { 
     List<SelectListItem> _projects = new List<SelectListItem>(); 
     _projects.Add(new SelectListItem() { Text = "Project...", Value = "0", Selected = selectedValue == 0 }); 
     foreach (var project in db.GetProjects()) 
     { 
      _projects.Add(new SelectListItem() 
      { 
       Text = project.Name, 
       Value = project.Id.ToString(), 
       Selected = selectedValue > 0 && selectedValue.Equals(project.Id) 
      }); 
     } 
     return _projects; 
    } 
} 

查看:

@using Project.DataAccess.DataModels 
@model List<TimeReport> 

@{ 
    ViewBag.Title = "TimeSheet"; 
    Layout = "~/Views/_Layout.cshtml"; 
    int index = 0; // i use this variables to manage collections with binder 
    int index2 = 0; 
} 

@using (Html.BeginForm()) 
{ 
foreach (TimeReport t in Model) 
{ 
    // 
    foreach (TimeEntry te in t.TimeEntries) 
    { 
     // 
     @Html.DropDownListFor(model => model[index].TimeEntries[index2].ProjectId, 
      (IEnumerable<SelectListItem>)ViewBag.Projects) 
     // 
     index2++; 
    } 
    // 
    index++; 
} 
<input type="submit" value="Submit" /> 
} 

此外,在萤火虫我看到:

<select name="[0].TimeEntries[0].ProjectId">  
    <option selected="selected" value="0">Project...</option> 
    <option value="1">First Project</option> 
    <option value="2">Second Project</option> 
</select> 

回答

0

好吧,它看起来像是用一个参数“0”调用你的“GetProjects”函数...所以它总是会选择那个第一个SelectItem。

ViewBag.Projects = h.GetProjects(0); 

希望有所帮助!