【问题标题】:MVC 4 - How to get the selected item from a dropdown listMVC 4 - 如何从下拉列表中获取所选项目
【发布时间】:2013-02-22 00:35:03
【问题描述】:

我对 MVC 很陌生。我有以下 Razor 代码:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset style="margin:5px">
        <legend>List a Bicycle for Sale</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.BicycleManfacturer)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ManufacturerList")
        </div>

        ....
        ....


        <div class="float-right">
            <input type="submit" value="List Bike" />
        </div>
    </fieldset>
}

“ManufacturerList”是存储在 ViewBag 中的 SelectedListItem 列表(我不想为所有下拉列表创建模型)。它是通过这种方法构建的:

    private void HydrateManufacturerList()
    {
        var manufacturerList = (from row in db.BicycleManufacturer.ToList()
                                select new SelectListItem
                                {
                                    Text = row.Description,
                                    Value = row.BicycleManufacturerId.ToString()
                                }).ToList();
        manufacturerList.Add(new SelectListItem
        {
            Text = "-- Select Manufacturer --",
            Value = "0",
            Selected = true
        });
        ViewBag.ManufacturerList = manufacturerList.OrderBy(row => row.Text);
    }

我有以下代码在提交完成时被调用:

    [HttpPost]
    public ActionResult Create(BicycleSellerListing bicyclesellerlisting)
    {
        bicyclesellerlisting.ListingDate = System.DateTimeOffset.Now;

        if (ModelState.IsValid)
        {
            db.BicycleSellerListing.Add(bicyclesellerlisting);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(bicyclesellerlisting);
    }

当用户将视图发布回我的控制器并执行此方法时,我不知道如何从下拉列表中获取所选制造商。

【问题讨论】:

  • 请在您的帖子中展示更多您的模型。你可以通过几种方式做到这一点。最好使用 lambda 和 DropDownListFor
  • 这个网站有很多相同的问题。请研究它们。特别是,@DaveA 建议(dropdownlistfor - strong-typed-helpers)
  • 使用 Html.DropDownListFor
  • @DaveA - 我添加了补充制造商列表的代码。
  • 请同时添加您的模型定义

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

使用

public ActionResult Create(BicycleSellerListing bicyclesellerlisting, FormCollection collection)
{ 
  ...

根据您的下拉列表名称,您可以获得所有输入,包括下拉选择的项目,如 collection["ManufacturerList"] 或类似的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2018-05-01
    • 2017-02-20
    • 2023-03-29
    相关资源
    最近更新 更多