在这里,我有一个Dropdownlistfor我的项目。但在这里我坚持得到选择的值。我尝试下面。但仍然无法从下拉列表中获取所选项目
@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();
}
答案 0 :(得分: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();
}