Showing posts with label Asp.Net Mvc. Show all posts
Showing posts with label Asp.Net Mvc. Show all posts

Saturday, June 6, 2015

ViewBag with Multiple SelectList in Asp.Net Mvc

     ViewBag used as a bag to move data from Controller toView. In my daily software life, use it frequently. In ViewBag you can store string, integer,. vs values or list. In View you can want to select multiple item from the list. Now i want to share how to select multiple items from list which store in ViewBag.

In Controller, get all personels with the _service.GetPersonel() method.To select multiple personels, should define Multiple before SelectList. If you select only one personel, can define new SelectList(). In ViewBag we shsould store personels' name and surname in Text, idtPersonel in Value.






  • In Controller

  •  public ICollection<int> idtPersonels{ get; set; }
    
    
            ViewBag.Personeller =  new MultiSelectList( (_service.GetPersonels())
              .Select(x => new SelectListItem
                            {
                                Text = x.Name+ " " + x.Surname+ " " + x.ID,
                                Value = x.idtPersonels.ToString()
                            }), "Value", "Text");



    In View, users store selected personels in idtPersonels. To use multiple property of  DropDownListFor , create class and call select2 and make  @multiple property  true. Please visit what is Select2 to get more info. 





  • In View

  •  <div class="form-group">
                                                            
          @Html.DropDownListFor(m => m.idtPersonels, (MultiSelectList)ViewBag.Personeller , new { @class = "form-control select2", @multiple = true })
                             
      </div>




    After select multiple personels in View, We can reach these selected personels like this.





  • In Controller

  •  public ActionResult GetPersonel(FormCollection form)
    {   
        //in form["idtPersonels"] store id like : {12,45,85}, and we must split them
       
     string[] listOfPersonel =           form["idtPersonels"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    }