DropDownListFor不与model属性绑定

时间:2012-02-06 22:32:54

标签: asp.net-mvc drop-down-menu

我不知道为什么dropdownlist在这种特殊情况下不起作用:

我知道,我有ProjectID> 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>

1 个答案:

答案 0 :(得分:0)

好吧,看起来您正在使用参数“0”调用“GetProjects”函数...所以它总是会选择第一个SelectItem。

ViewBag.Projects = h.GetProjects(0);

希望有所帮助!