0

I have this query to get the data inserted in my db

var groups = (from group_s in _context.Groups
              select new SelectListItem()
              {
                 Text = group_s.GroupName,
                 Value = group_s.GroupId.ToString(),
              }).ToList();
ViewBag.Groups = groups;

and this my html select tag

<select class="select2 form-control" 
        asp-for="@Model.Group" 
        asp-items="@(new SelectList(ViewBag.Groups,"Value", "Text"))" 
        multiple>
</select>

my problem is how to get the items selected in my form, please someone have any idea ?

1

1 Answer 1

0

Try following.

View Page

@model Core_Web_App_MVC.Controllers.MyGroupModel

<form method="post">
    @Html.ListBoxFor(m => m.SelectedGroups, new MultiSelectList(ViewBag.Groups, "Value", "Text"), null)
    <input type="submit" value="Submit" />
</form>

Controller Code

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace Core_Web_App_MVC.Controllers
{
    public class MyGroupModel
    {
        public List<int> SelectedGroups { get; set; }
    }
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            List<SelectListItem> groups = new List<SelectListItem>();
            groups.Add(new SelectListItem() { Text = "Group 1", Value = "1" });
            groups.Add(new SelectListItem() { Text = "Group 2", Value = "2" });
            groups.Add(new SelectListItem() { Text = "Group 3", Value = "3" });
            ViewBag.Groups = groups;

            MyGroupModel myGroupModel = new MyGroupModel();
            myGroupModel.SelectedGroups = new List<int>();

            return View(myGroupModel);
        }

        [HttpPost]
        public IActionResult Index(MyGroupModel data)
        {
            return View(data);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.