Null Pointer
Null Pointer

Reputation: 9289

Restrict selection to single select of a listboxFor- MVC 2

I am using following code to generate a list box..

    <%: Html.ListBoxFor(m => m.Subscribers, new List<SelectListItem>(), new { @class = "list_style_Wizard" })%>

But we can select more than one items from the listbox.. How can i restric it to single select ???

Upvotes: 4

Views: 7981

Answers (2)

Glenn
Glenn

Reputation: 688

The HTML helpers DropDownListFor and ListBoxFor seem to add the multiple attribute when rendering as a listbox. I use a combination of the DropDownListFor/ListBoxFor and a jQuery livequery selector to remove the multiple attribute. In Razor use:

@Html.DropDownListFor(m => m.SelectedId, Model.SelectList, 
    new { size = 10, @class = "selectOneListBox" })

and in JavaScript:

$(".selectOneListBox").livequery(function () {
    $(this).removeAttr('multiple');
});

I'm sure you could also write your own version of the HTML helper routine that doesn't spit out the multiple attribute.

Upvotes: 10

David Glenn
David Glenn

Reputation: 24522

Html.ListBoxFor is used to render a multiple choice list box. For single choice use Html.DropDownListFor

<%: Html.DropDownListFor(m => m.Subscribers, listOfsubscribers, new { @class = "list_style_Wizard" }) %>

Upvotes: 6

Related Questions