如何将return一个值列表 改为post?

How to return a list of values ​to the post?

我是新手,不知道怎么做,希望大家帮帮我

我在视图中使用列表框来使用多选。碰巧在选择它们和创建它们时,它只取所选产品的第一个值,但我希望它捕获所有选择的值。

在我的控制器中,我执行以下操作

var producto=db.productos.select(x=> new { idprod=x.id_prod, nombre=nombre_prod}).tolist();
ViewBag.producto=new multiselect(producto,"idprod","nombre");

在我的站点中

@html.listbox(model=>model.idprod, viewbag.producto as multiselectlist)

如果你想用表达式来表示对象属性,你可以尝试使用Html.ListBoxFor,而不是Html.ListBox

请参考以下示例:

public class Customer
{
    public string CustomerName { get; set; }

    public string[] FavouriteFood { get; set; }
}
//used to add listbox items
public class Food
{
    public int FoodId { get; set; }
    public string FoodName { get; set; }
}

控制器:

    public IActionResult CreateSurvey()
    {
        //listbox items:
        ViewBag.FoodList = new List<Food>()
        {
            new Food(){ FoodId=101, FoodName="Meat"},
            new Food(){FoodId=102, FoodName="Fruit"},
            new Food(){FoodId=103, FoodName="Fish"}
        }; 
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult CreateSurvey(Customer customer)
    {
        ViewBag.FoodList = new List<Food>()
        {
            new Food(){ FoodId=101, FoodName="Meat"},
            new Food(){FoodId=102, FoodName="Fruit"},
            new Food(){FoodId=103, FoodName="Fish"}
        };

        //loop through the selected value and do something
        return View();
    }

视图中的代码:

@model netcore5.Models.Customer
 
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateSurvey">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="CustomerName" class="control-label"></label>
                <input asp-for="CustomerName" class="form-control" />
                <span asp-validation-for="CustomerName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FavouriteFood" class="control-label"></label>
                @Html.ListBoxFor(model =>model.FavouriteFood, new SelectList((List<Food>)ViewBag.FoodList, "FoodId","FoodName") )
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

结果是这样的:

如果要使用Html.ListBox()方法,修改相关代码如下:

   @Html.ListBox("FavouriteFood", new SelectList((List<Food>)ViewBag.FoodList, "FoodId","FoodName") )

然后在action方法中,我们也可以获取到选中的值