简体   繁体   中英

How to use multi selection in ASP.NET MVC application?

Two days already I am trying to figure out and learn how to build multi-selection dropdown list in ASP.NET Core, that is seeded from db context, and results are used further in the constructor, so I decided to ask this question. I did not find anywhere how to use data from posted form, so maybe you will be able to help me. I belive that I did some mistakes in my POST action in controller. I am not sure how I am supposed to get posted data into the controller.

I was trying various combinations on simple example. Best what I have now is:

ViewModel.cs:

public class ProductViewModel
    {
        public List<SelectListItem> Products { get; set; }
        public int[] ProductIDs { get; set; }
    }

Index.cshtml:

<!DOCTYPE html>
<html>
<head>
    <title>Aplikacja</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="~/dist/allstyles.css" />
</head>
<body>
    <form asp-action="Index" method="post">
        <input type="hidden" asp-for="Products" />

        <div class="form-group">
            <label asp-for="Products">Produkty</label>
            <select asp-for="ProductIDs" class="form-control" asp-items="ViewBag.Lista"></select>
        </div>
        <div class="text-center">
            <button class="btn btn-primary" type="submit">Save</button>
            <a asp-action="Index" class="btn btn-secondary">Cancel</a>
        </div>
    </form>

//ViewBag tests from controller
    @ViewBag.Message  //test1, returns 0
    @ViewBag.Message2 //test2, returns 0

</body>
</html>

Controller.cs

public class ProductController : Controller
{
    private readonly ApplicationDbContext _context; //database context

    public ProductController(ApplicationDbContext context)
    {
        _context = context; //context for controller
    }
    //GET
    public ActionResult Index()
    {
        ProductViewModel productVM = new ProductViewModel(); //viewmodel instance
        PopulateProducts(); //populating dropdown
        return View(productVM); //returning viewmodel
    }
    //POST (I belive that here I have screwed something a lot, I do not understand everything what is going on in this action)
    [HttpPost]
    public ActionResult Index(ProductViewModel productVM)
    {
        PopulateProducts(); 

        if (productVM.ProductIDs !=null)
        {
            List<SelectListItem> selectedItems = productVM.Products.Where(p => productVM.ProductIDs.Contains(int.Parse(p.Value))).ToList();

            ViewBag.Message = selectedItems.Count.ToString(); //returns 0
            ViewBag.Message2 = productVM.Products.Count.ToString();//returns 0
        }
        return View(productVM);
    }

    private void PopulateProducts() //method populating dropdown list
    {

        var techQuery = from t in _context.Products //getting products context from database
                        orderby t.Name //sorting by names
                        select t; //selecting item (??)

        if (techQuery != null) //if db context var is not null...
        {
            ViewBag.Lista = techQuery.Select(n => new SelectListItem { Text = n.Name, Value = n.ProductID.ToString() }); //...creating viewbag that is used for populating dropdown list in view

        }
    }
}

For selectedItems , I think you need to retrive from ViewBag.Lista instead of productVM.Products . When Posting Form from View to Controller , ProductViewModel.Products will always be null.

I suggest you try workaround below by using ViewBag.Lista .

    public ActionResult ProductSelect(ProductViewModel productVM)
    {
        PopulateProducts();

        if (productVM.ProductIDs != null)
        {
            List<SelectListItem> selectedItems = ((IEnumerable<SelectListItem>)ViewBag.Lista)
                .Where(p => productVM.ProductIDs.Contains(int.Parse(p.Value))).ToList();

            ViewBag.Message = selectedItems.Count.ToString(); //returns 0
            ViewBag.Message2 = ((IEnumerable<SelectListItem>)ViewBag.Lista).Count().ToString();//returns 0
        }
        return View(productVM);
    }

The solution is pretty simple & You're almost there. I am going to suggest few of the changes. In ViewModel.cs, it is good idea to populate the list property thru a constructor. It avoids Null Reference exceptions & makes it easy to use the object.

 public ProductViewModel()
    {
        Products=new List<SelectListItem>();
    }
    public List<SelectListItem> Products { get; set; }
    public int[] ProductIDs { get; set; }

In controller.cs, I would make changes to return PopulateProducts to return List Of SelectList, rather than populating view bag. Note: Please close the DB Connection as you will run out connection pools eventually.

public class ProductController : Controller
{
    private readonly ApplicationDbContext _context; //database context

    public ProductController(ApplicationDbContext context)
    {
        _context = context; //context for controller
    }
    //GET
    public ActionResult Index()
    {
        ProductViewModel productVM = new ProductViewModel(); //viewmodel instance
        productVM.Products=PopulateProducts(); //populating dropdown

        return View(productVM); //returning viewmodel
    }
    //POST (I belive that here I have screwed something a lot, I do not understand everything what is going on in this action)
    [HttpPost]
    public ActionResult Index(ProductViewModel productVM)
    {
        productVM.Products= PopulateProducts();

        if (productVM.ProductIDs != null)
        {
            List<SelectListItem> selectedItems = productVM.Products.Where(p => productVM.ProductIDs.Contains(int.Parse(p.Value))).ToList();

            ViewBag.Message = selectedItems.Count.ToString(); //returns 0
            ViewBag.Message2 = productVM.Products.Count.ToString();//returns 0
        }
        return View(productVM);
    }

    private List<SelectListItem> PopulateProducts() //method populating dropdown list
    {

        var techQuery = from t in _context.Products //getting products context from database
            orderby t.Name //sorting by names
            select t; //selecting item (??)

        if (techQuery != null) //if db context var is not null...
        {
            return techQuery.Select(n => new SelectListItem { Text = n.Name, Value = n.ProductID.ToString() }).ToList(); //...creating viewbag that is used for populating dropdown list in view

        }

        return null;
    }
}

Finally, in index.cshtml, you need to specify the model that is expected for the view & populate product ids from @Model.Products.

@model ProductViewModel
<form asp-action="Index">
<div class="form-group">
    <label asp-for="Products">Products</label>
    <select asp-for="ProductIDs" class="form-control" asp-items="@Model.Products"></select>
</div>
<div class="text-center">
    <button class="btn btn-primary" type="submit">Save</button>
    <a asp-action="Index" class="btn btn-secondary">Cancel</a>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM