Amjad Nasser Amjad Nasser - 1 year ago 169
ASP.NET (C#) Question

Display Checkbox items in Dropdown list (MVC)

My checkbox items works very well. however, I need to display it as dropdown list

here's the list in the BookViewModel.cs (the model displayed in my view)

public List<CheckBoxViewModel> Authors { get; set; }

this is The CheckBoxViewModel.cs

public class CheckBoxViewModel
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }

This my controller (which adds the items into the Authors in checkboxViewModel

var Results = from b in
select new
name = b.first_name + " " + b.middle_name + " " + b.last_name,

var MyViewModel = new BooksViewModel();

var MyCheckBoxList = new List<CheckBoxViewModel>();
foreach (var item in Results)
MyCheckBoxList.Add(new CheckBoxViewModel { Id = item.authorID, Name =});

MyViewModel.Authors = MyCheckBoxList;

and finally this is how i display the checkbox items in my view Create.cshtml

<div class="form-group">
@Html.LabelFor(model => model.Authors, ": المؤلف/ المؤلفين", htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-6">

<div style="text-align:right">
@for (int i = 0; i < Model.Authors.Count(); i++)

@Html.DisplayFor(m => Model.Authors[i].Name) <text> </text>
@Html.EditorFor(m => Model.Authors[i].Checked)

@Html.HiddenFor(m => Model.Authors[i].Name)
@Html.HiddenFor(m => Model.Authors[i].Id)
<br />
<text class="text-danger"> @ViewBag.empty_authors</text>
@Html.ActionLink("مؤلف جديد ", "CreateAuthor", "books", new { Model }, new { @class = "modal-link btn btn-success", @style = "font-size:20px" })<br />
<div class="col-md-4">
@*@Html.ListBoxFor(model => model.authorID, new SelectList(ViewBag.authorID, "a_id", "fullname"), htmlAttributes: new { @multiple = "multiple", @class = "form-control" })*@

@Html.ValidationMessageFor(model => model.Authors, "", new { @class = "text-danger" })

pleaese note that I don't use any JQuery / scripts till in my code till now, if there's any way to display the checkbox items in dropdownlist using C# in my controller it'll be preferable

Thank you .

PS. if there's a solution using JavaScripts please describe it in details.

I decided to fix the height of the div that contains my list of Authors in Create.cshtml view and I allow it to be scroll-able in y-axis, i find it an acceptable solution for my problem so no need for extra javascript code .

Answer Source

you can't, you will have to find a jquery plugin to do so.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download