0

在这里,我的项目有一个下拉列表。但在这里我坚持获取选定的值。我的尝试如下。但仍然无法从下拉列表中获取选定的项目

@Html.DropDownListFor(m => m.ProductType, (SelectList)ViewBag.ListOfCategories, new { @class = "form-control"})

型号代码

[Required]
        public string ProductType { get; set; }

控制器

 [HttpPost]
    public ActionResult AddProduct(ICS.Models.ProductsModels.Products model)
    {
        ProductController _ctrl = new ProductController();
        _ctrl.AddorUpdateProduct(new ICS.Data.Product
        {
            ProductName = model.ProductName,
            ProductType = model.ProductType,
            IsFixed = model.PriceSettings,
            ItemPrice = model.ItemPrice,
            PurchasePrice = model.PurchasePrice,
            Vat = model.Vat,
            WholeSalePrice = model.WholeSalePrice,
            Comments = model.Comments
        });
        return View(model);
    }


[HttpGet]
    public ActionResult AddProduct()
    {
        ViewBag.ListOfCategories = new SelectList(_cat.GetCategory(), "CategoryId", "CategoryName");
        return View();
    }
4

1 回答 1

1

我建议 Razor 只是不明白什么是文本以及下拉列表选项中的值必须是什么,因此它只会生成空下拉列表(无值属性)。你可以检查你渲染的html,我想它看起来像

<select>
   <option>Category1Name</option>
   <option>Category2Name</option>
   <option>Category3Name</option>
   ...
</select>

你应该IEnumerable<SelectListItem>用作下拉菜单的来源。例子:

[HttpGet]
public ActionResult AddProduct()
{
    // this has to be the list of all categories you want to chose from
    // I'm not shure that _cat.GetCategory() method gets all categories. If it does You
    // should rename it for more readability to GetCategories() for example
    var listOfCategories = _cat.GetCategory();

    ViewBag.ListOfCategories = listOfCategories.Select(c => new SelectListItem {
        Text = c.CategoryName,
        Value = c.CategoryId
    }).ToList();

    return View();
}
于 2013-11-11T05:27:38.370 回答