Phi*_*enn 1 asp.net-mvc viewmodel html.dropdownlistfor razor asp.net-mvc-4
我正在关注ASP.NET MVC的这个教程,特别是它声明提供"MovieType"Razor View 的String 如下:@Html.DropDownList("MovieType")将提供DropDownList的键以查找ViewBag类型的属性IEnumerable<SelectListItem>.
这很好用.
但是,我无法获取用户在带有[HttpPost]属性的方法上选择的值.
这是我的代码和迄今为止我尝试过的内容.
调节器
public class ProductController : Controller 
{
    private readonly ProductRepository repository = new ProductRepository();
    // Get: /Product/Create
    public ActionResult Create()
    {
        var categories = repository.FindAllCategories(false);
        var categorySelectListItems = from cat in categories
                                      select new SelectListItem()
                                          {
                                              Text = cat.CategoryName,
                                              Value = cat.Id.ToString()
                                          };
        ViewBag.ListItems = categorySelectListItems;
        return View();
    }
    [HttpPost]
    public ActionResult Create(Product product)
    {
        /** The following line is not getting back the selected Category ID **/
        var selectedCategoryId = ViewBag.ListItems;
        repository.SaveProduct(product);
        return RedirectToAction("Index");
    }
}
Razor cshtml查看
@model Store.Models.Product
<h2>Create a new Product</h2>
@using (@Html.BeginForm())
{
    <p>Product Name:</p>
    @Html.TextBoxFor(m => m.ProductName)
    <p>Price</p>
    @Html.TextBoxFor(m => m.Price)
    <p>Quantity</p>
    @Html.TextBoxFor(m => m.Quantity)
    <p>Category</p>
    @Html.DropDownList("ListItems")
    <p><input type="submit" value="Create New Product"/></p>
}
我尝试使用重载DropDownList,但我无法获得用户选择的值.
如果有人看到我缺少的或有任何想法或建议,我将非常感激.谢谢!
更新
发布Product模型.注意,当我创建.edmx时,这是由Entity Framework自动生成的.
namespace Store.Models
{
    using System;
    using System.Collections.Generic;
    public partial class Product
    {
        public long Id { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public System.DateTime DateAdded { get; set; }
        public Nullable<long> CategoryId { get; set; }
        public virtual Category Category { get; set; }
    }
}
您正在将类型模型传递Store.Models.Product到视图中.其他字段使用lambda表达式绑定到此模型,但@Html.DropDownList()不绑定到模型,因此当在HTTPPost中返回模型时,选择不存在.
您需要将Category字段添加Store.Models.Product到该列表,然后使用以下命令绑定到该列表:
@Html.DropDownListFor(m => m.Category, ViewBag.ListItems)
然后MVC应该正确地将输入控件绑定到模型.
作为示例,此语法确实有效:
int[] listItems = {1, 2, 3, 4};
SelectList selectList = new SelectList(listItems);
@Html.DropDownListFor(m => m.CategoryId, selectList);
请注意,SelectList继承自MultiSelectList哪些实现IEnumerable<SelectListItem>.
| 归档时间: | 
 | 
| 查看次数: | 21591 次 | 
| 最近记录: |