我必须使用@Html.CheckBoxListFor<> 或@Html.DropdownListFor<>。当我使用List 进行模型绑定时,我对如何在View 中使用这些帮助程序类感到困惑。
将 List 绑定到 CheckBoxList 和 DropdownList 的正确和最简单的方法是什么。
在模型中:
public class SampleViewModel
{
public IEnumerable<Responsible> AvailableResponsibles { get; set; }
public IEnumerable<Responsible> SelectedResponsibles { get; set; }
public PostedResponsibles PostedResponsibles { get; set; }
Responsible objResponsible = new Responsible();
public SampleViewModel GetResponsiblesInitialModel()
{
//setup properties
var model = new SampleViewModel();
var selectedResponsibles = new List<Responsible>();
//setup a view model
model.AvailableResponsibles = objResponsible.GetAll().ToList();
model.SelectedResponsibles = selectedResponsibles;
return model;
}
}
public class Responsible
{
//Integer value of a checkbox
public int Id { get; set; }
//String name of a checkbox
public string Name { get; set; }
//Boolean value to select a checkbox
//on the list
public bool IsSelected { get; set; }
//Object of html tags to be applied
//to checkbox, e.g.:'new{tagName = "tagValue"}'
public object Tags { get; set; }
public IEnumerable<Responsible> GetAll()
{
return new List<Responsible> {
new Responsible {Name = "Apple", Id = 1 },
new Responsible {Name = "Banana", Id = 2},
new Responsible {Name = "Cherry", Id = 3},
new Responsible {Name = "Pineapple", Id = 4},
new Responsible {Name = "Grape", Id = 5},
new Responsible {Name = "Guava", Id = 6},
new Responsible {Name = "Mango", Id = 7}
};
}
}
public class PostedResponsibles
{
//this array will be used to POST values from the form to the controller
public string[] ResponsibleIds { get; set; }
}
和视图是:
<tr>
<td>
@Html.LabelFor(model=>model.Responsible)
</td>
<td>
@Html.CheckBoxListFor(model => model.PostedResponsibles.ResponsibleIds,
model => model.AvailableResponsibles,
Responsible => Responsible.Id,
Responsible => Responsible.Name,
model => model.SelectedResponsibles)
</td>
</tr>
目前我正在使用 Nuget Packege,但它有点令人困惑且难以使用。建议我使用其他任何方法来实现这一目标。