I have to use @Html.CheckBoxListFor<> or @Html.DropdownListFor<>.I am confused about how to use these helper class in View whild I am using List for Model Binding.
What is the Right and Easiest way to Bind List into CheckBoxList and DropdownList.
In Model:
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; }
}
And View Is:
<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>
Currently I am using Nuget Packege but it is little bit confusing and hard to use.Suggest me any other to achieve this one.
It depend on your UI requirement. if you need a drop down list then use that.
CheckBoxList is not out of the box helper, it is a custom helper.
You can find more details of the helper (CheckBoxList) from here Code Project
Regarding Drop down please refer to MSDN. It can be overloaded in multiple ways.
Here are the available ASP.NET MVC helpers
Step Install package using package manager
Add Fruit.cs
Add FruitViewModel.cs
Add PostedFruits.cs
Add HomeController.cs
Add FruitRepository.cs
Add Index.cshtml