How to set multiple selected value and show them in dropdownlist with MVC?

Dondon510 221 Reputation points
2022-08-04T08:08:26.98+00:00

How to set multiple selected value and show them in dropdownlist with MVC?

my .cshtml

<div class="col-6 mb-1">  
        <label class="form-label" for="">Members</label>  
              <div class="input-group input-group-merge">  
                       @Html.DropDownListFor(x => x.members, Model.memberList, new { @id="Members", @class= "select2 form-select",  multiple =   
                               "multiple", tabindex="3" });   
                        <span asp-validation-for="members" class="text-danger"></span>  
               </div>  
</div>  

.js

$(window).on('load', function() {

        $("#Members").select2();  

});  

Class

  public long[] members { get; set; }  
  public SelectList memberList { get; set; } = Load_Members()  

LoadMembers();

 while (dr.Read())  
  {  
        list.Add(new SelectListItem() { Value = dr.GetInt64(dr.GetOrdinal("pid")).ToString(), Text = dr.GetString(dr.GetOrdinal("member_name")) });  
   }  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,156 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2022-08-04T15:16:04.29+00:00

    The proper way is to initial the members array with the desired values. When the select tag helpers builds the options array, if the option values is in members it will select it.

    1 person found this answer helpful.
    0 comments No comments

  2. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-08-05T07:41:57.047+00:00

    Hi @Dondon510 ,

    In the class, you can add a string type property to store the selected members with the delimiter, like this:

        public class Select2Model  
        {  
            public long[] members { get; set; }  
    
            public string selectedmembers { get; set; } //used to store the selected members, such as: "tom,johnn,david"  
            public SelectList memberList { get; set; } = Load_Members();  
    
            public static SelectList Load_Members()  
            {  
                List<SelectListItem> list = new List<SelectListItem>()  
                {  
                    new SelectListItem(){ Value="tom", Text="Tom"},  
                     new SelectListItem(){ Value="jack", Text="Jack"},  
                      new SelectListItem(){ Value="johnn", Text="Johnn"},  
                       new SelectListItem(){ Value="vivian", Text="Vivian"},  
                        new SelectListItem(){ Value="david", Text="David"},  
                };  
    
    
                return new SelectList(list,"Value","Text");  
            }  
        }  
    

    Then, in the view page(.cshtml), use a hidden field to store the selectedmembers :

            <input type="hidden" id="selectedmemebers" value="@Model.selectedmembers" />  
        @Html.DropDownListFor(x => x.members, Model.memberList, new { @id="Members", @class= "select2 form-select",  multiple =   
                "multiple", tabindex="3" })  
            <span asp-validation-for="members" class="text-danger"></span>  
    

    After that using the following scripts to set the default selected value: 228481-javascipts.txt

    228389-image.png

    In the controller:

        public IActionResult Select2Index()  
        {  
            var select2model = new Select2Model();  
            select2model.selectedmembers = "tom,johnn,david"; //set the default selected members  
            return View(select2model);  
        }  
    

    Finally, the result is like this:

    228426-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

  3. SurferOnWww 1,906 Reputation points
    2022-08-08T00:48:37.507+00:00

    How to set multiple selected value and show them in dropdownlist with MVC?

    I suggest that you use the MultiSelectList. Shown below is sample:

    Model

    Note that the MultiSelectList is used.

    public class MultiCategoryViewModel  
    {  
        public int[] Category { get; set; }  
       
        public MultiSelectList Categories { get; set; }  
    }  
    

    Controller / Action Method

    public async Task<IActionResult> Edit3()  
    {  
        int[] selected = new int[] { 1, 3, 5 };  
        var categoryList = await _context.Categories.ToListAsync();  
       
        ViewBag.CategoryId = new MultiSelectList(categoryList,  
                                                 "CategoryId",  
                                                 "CategoryName",  
                                                 selected);  
       
        var model = new MultiCategoryViewModel  
        {  
            Category = selected,  
            Categories = new MultiSelectList(categoryList,  
                                             "CategoryId",  
                                             "CategoryName")  
        };  
       
        return View(model);  
    }  
       
    [HttpPost]  
    [ValidateAntiForgeryToken]  
    public IActionResult Edit3(int[] categoryid,   
                               int[] categoryid2,   
                               int[] category)  
    {  
        if (ModelState.IsValid)  
        {  
            return RedirectToAction("Index");  
        }  
       
        return View();  
    }  
    

    View

    @model MvcCore5App.Controllers.MultiCategoryViewModel  
       
    @{  
        ViewData["Title"] = "Edit3";  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  
       
    <h1>Edit3</h1>  
       
    <div class="row">  
        <div class="col-md-4">  
            <form asp-action="Edit3">  
                <div class="form-group">  
                    <label class="control-label" for="CategoryId">  
                        @@Html.DropDownList 利用  
                    </label>  
                    @Html.DropDownList("CategoryId", null,  
                        htmlAttributes: new  
                        {  
                            @class = "form-control",  
                            multiple = "multiple"  
                        })  
                </div>  
                <div class="form-group">  
                    <label class="control-label" for="CategoryId2">  
                        タグヘルパー &lt;select&gt; + ViewBag 利用  
                    </label>  
                    <select id="categoryid2" name="categoryid2"  
                            asp-items="@ViewBag.CategoryId"  
                            multiple="multiple"  
                            class="form-control">  
                    </select>  
                </div>  
                <div class="form-group">  
                    <label class="control-label" for="CategoryId2">  
                        タグヘルパー &lt;select&gt; + Model 利用  
                    </label>  
                    <select asp-for="Category"  
                            asp-items="Model.Categories"  
                            class="form-control">  
                    </select>  
                </div>  
                <div class="form-group">  
                    <input type="submit" value="Create"  
                           class="btn btn-primary" />  
                </div>  
            </form>  
        </div>  
    </div>  
    

    Result:

    228921-image.jpg

    0 comments No comments