How to set a option on Chosen.js via server side?

777 views Asked by At

Im developing a website using ASP.NET MVC 5, with a multiple select using Chosen.js. My action is this:

    [HttpGet]
    public ActionResult Get()
    {       
           var states = GetStates();      
            ViewBag.States = new SelectList(states.OrderBy(o => o.Id), "Value", "Name");
            return View();            
    }

And in the view:

 @Html.ListBoxFor(m => m.States,
        ViewBag.States as SelectList, new Dictionary<string, object>
        {
            {"multiple", "multiple"},
            {"class", "chosen-container-multi"},
            {"placeholder", "State"},
            {"id", "State"}
        });

It works fine, but I would like to pré select the user state before load the page. Perhaps something like:

     ViewBag.States = new SelectList(states.OrderBy(o => o.Id), "Value", "Name","UserStateId");

but it not works. Is there a way to do that?

2

There are 2 answers

2
gog On BEST ANSWER

I went to this approach:

Created a new string property on the model called UserState, then i get the user state and assign it to that property:

ViewBag.States= new SelectList(states.OrderBy(o => o.Id), "Value", "Name");
var model = new ModelDTO {  UserState = states.Single(p => p.Id.Equals(stateId)).Value};
 return View(model);

Then on the view i simply get it:

  @Html.ListBoxFor(m => m.States,
    ViewBag.States as SelectList, new Dictionary<string, object>
    {
        {"multiple", "multiple"},
        {"class", "chosen-container-multi"},
        {"placeholder", "State"},
        {"id", "State"}
    });

 <script>
    $(function () {
        $("#StatesListBox").chosen();
        $('#StatesListBox').val("@Model.UserState");
        $('#StatesListBox').trigger("chosen:updated");
    });
</script>
2
AudioBubble On

Firstly you can't name the ViewBag property the same as your model property. Your listbox is binding to your model property States so the options that are selected will be based on the value of States. Since your not returning a model to your view States is null, therefore no options are selected.

Start by using a view model that represents what you want to display/edit in the view

public class MyViewModel
{
  public int[] SelectedStates { get; set; }
  public SelectList StatesList { get; set; }
} 

Controller (note I'm assuming here that State contains a property int Id (to bind to) and a property string Name (the display value) and that you want to preselect the states with Id=2 and Id=5)

[HttpGet]
public ActionResult Get()
{ 
  MyViewModel model = new MyViewModel();      
  var states = GetStates().OrderBy(o => o.Id);
  model.StatesList = new SelectList(states, "Id", "Name");  
  model.SelectedStates = new int[] { 2, 5 }; // set the value of the options you want to preselect
  return View(model);            
}

View

@Html.ListBoxFor(m => m.SelectedStates, Model.StatesList, new { @class = "chosen-container-multi" })

Assuming you have 10 States with Id between 1 and 10, then the 2nd and 5th options will now be selected when the page is first rendered. When you submit your form, property SelectedStates will contain and array of the values selected by the user.

Side note: ListBoxFor() already adds the attributes multiple="multiple" and id="SelectedStates"