18

I want to use multiple select in Chosen. I have Skill model like,

public class Skill 
    {
        public int Id { get; set; }
        public string Name { get; set; }        
    }

This works in my application:

    <select data-placeholder="Choose a Country..." class="chzn-select" multiple >
           <option value=""></option>
           <option value="United States">United States</option>
           <option value="Albania">Albania</option>
           <option value="Algeria">Algeria</option>
   </select>

I want to replace Countries data with my data. In controller i write:

        var list = MyService.LoadAllSkills();
        ViewBag.Skills = new MultiSelectList(list, "Id", "Name");

In view:

@Html.ListBox("Name", ViewBag.Skills as MultiSelectList,
              new { @class = "chzn-select" } )

View result of @Html.ListBox() and @Html.DropDownList() is not like <select>

I get so result:

enter image description here

But, I want to get result as

enter image description here

How can I change Chosen sample?

2
  • try any jquery plugin for that. Dec 8, 2012 at 13:49
  • @Kundan Singh Chouhan, can you share any other link? for other plugin Dec 8, 2012 at 17:08

2 Answers 2

14

The only difference I can see between the hardcoded example (which you stated that is working) and the one you generate with the ListBox helper is the absence of the data-placeholder attribute. So:

@Html.ListBox(
    "Countries", 
    ViewBag.Skills as MultiSelectList,
    new { @class = "chzn-select", data_placeholder = "Choose a Country..." } 
)

This should at least generate the same markup as what you said is working. If it doesn't work then probably you haven't setup the plugin correctly or you have some other javascript errors. Read the documentation of the plugin about how it should be setup.

1
  • 2
    Then you probably have some other issue with setting the plugin which has strictly nothing to do with ASP.NET MVC. As far as the server side code is concerned, it should generate strictly equivalent markup to what you have shown in your question. Also notice that when using data_placeholder on the server side, the helper will automatically convert this to data-placeholder when generating the corresponding attribute. Dec 8, 2012 at 16:46
0

as other dudes mentioned, it seems your problem cause is not server-side (razor), it's actually client-side (most probably your Jquery plugin initialization).

probably when the plugin initialization called the html DOM is not generated yet, put your plugin initialization script at the end of the body or inside $(document).ready() and don't forget to take a look at the console to see if there is any errors

happy coding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.