Wednesday 21 September 2016

Simulating multiple dropdown list with check box in MVC Entity frame work

 Model
 public class ViewModelClass
{
 public List<CheckBoxList> checkBoxList{ get; set; }
}
public class CheckBoxList
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }

Controllers
 public async Task<ActionResult> Create()
{
ViewModelClass model=new ViewModelClass();
model.checkBoxList=.db.fromTable.AsEnumerable().Select(x => new CheckBoxList()
              {
                    Id = x.Id,
                    Name = x.Name,
                    IsChecked = false,//first time creating so false
                }).ToList();
return view(model)
 }
VIEW
<style>
.dropdown-div
{
    overflow-y:scroll !important;
    height:100px !important;
    width:280px !important;
    padding-top: 6px;
    padding-right: 12px;
    padding-bottom: 6px;
    padding-left: 12px;
}
</style>
 <div class="form-control dropdown-div" id="SelectedItemsDiv">
                    @for (int i = 0; i < Model.checkBoxList.Count; i++)
                    {
                        @Html.HiddenFor(model => Model.checkBoxList[i].Id)

                        @Html.CheckBoxFor(model => Model.checkBoxList[i].IsChecked, new { @class = "" })
                        @Html.DisplayFor(model => Model.checkBoxList[i].Name) <br />
                    }
                </div>
//its for dynamic client side creation any on-change based loading list
 
$.each(Items, function (i, iteam) {
 $("#SelectedItemsDiv").append('<input id="checkBoxList_' + i +
                                  '__Id" name="
checkBoxList[' + i + '].Id" type="hidden" value="' + iteam.Value + '"><input class="" id="checkBoxList_' + i +
                                  '__IsChecked" name="
checkBoxList[' + i + '].IsChecked" type="checkbox" value="true"><input name="checkBoxList[' + i + '].IsChecked" type="hidden" value="false">' + iteam.Text + ' <br>')

CONTROLLER POST ACTION GET DATA
 public async Task<ActionResult> Create(ViewModelClass model)
        {

int[] selectedIteams = model.checkBoxList.Where(x => x.IsChecked == true).Select(x => x.Id).ToArray();
                    if(selteams.Length>0 && selteams!=null)
                    {

                             //get only checked items id
                     } 
return RedirectToAction("Index");//redirect to list

 




No comments:

Post a Comment