如何在 ASP.NET MVC 应用程序中使用多选?

两天前,我正在尝试弄清楚并学习如何在 ASP.NET Core 中构建多选下拉列表,该列表是从 db 上下文中生成的,并且结果在构造函数中进一步使用,所以我决定提出这个问题。我在任何地方都找不到如何使用已发布表单中的数据,所以也许您可以帮助我。我相信我在控制器中的 POST 操作中犯了一些错误。我不确定我应该如何将发布的数据输入控制器。


我在简单的例子上尝试了各种组合。我现在最好的是:


视图模型.cs:


public class ProductViewModel

    {

        public List<SelectListItem> Products { get; set; }

        public int[] ProductIDs { get; set; }

    }

索引.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>

控制器.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

    }


海绵宝宝撒
浏览 221回答 2
2回答

郎朗坤

对于selectedItems,我认为您需要从而ViewBag.Lista不是检索productVM.Products。当Form从Viewto发布时Controller,ProductViewModel.Products将始终为 null。我建议您尝试使用以下解决方法ViewBag.Lista。&nbsp; &nbsp; public ActionResult ProductSelect(ProductViewModel productVM)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; PopulateProducts();&nbsp; &nbsp; &nbsp; &nbsp; if (productVM.ProductIDs != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<SelectListItem> selectedItems = ((IEnumerable<SelectListItem>)ViewBag.Lista)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(p => productVM.ProductIDs.Contains(int.Parse(p.Value))).ToList();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ViewBag.Message = selectedItems.Count.ToString(); //returns 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ViewBag.Message2 = ((IEnumerable<SelectListItem>)ViewBag.Lista).Count().ToString();//returns 0&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return View(productVM);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP