简体   繁体   English

DropDownListFor不与模型属性绑定

[英]DropDownListFor is not binding with model property

I do not know why dropdownlist is not working in this particular case: 我不知道为什么dropdownlist在这种情况下不起作用:

I know, that i have ProjectID > 0, but in dropdownlist i always see first item selected. 我知道,我的ProjectID> 0,但是在下拉列表中,我总是看到选择的第一项。

Controller: 控制器:

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);
}     

Helper: 帮手:

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;
    }  
}

View: 视图:

@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" />
}

Also in firebug i see: 在萤火虫中我也看到:

<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>

Well, it looks like you are calling your "GetProjects" function with a parameter of "0"... so it will always select that first SelectItem. 好吧,看来您正在使用参数“ 0”调用“ GetProjects”函数...因此它将始终选择该第一个SelectItem。

ViewBag.Projects = h.GetProjects(0);

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM