ASP.NET MVC从下拉列表中选择值

时间:2011-08-17 16:06:45

标签: asp.net-mvc-3 drop-down-menu viewmodel

我有下一个模型(简化):

public class CarType
{
    public int Id { get; set; }

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

public class Car
{
    [Required]
    public string Model { get; set; }

    [Required]
    public CarType Type { get; set; }

    [Required]
    public decimal Price { get; set; }
}

我希望让用户从“创建”页面的下拉列表中选择汽车类型。 我试图通过ViewBag传递数据库中的类型字典及其名称:

ViewBag.Types = _context.CarTypes.ToDictionary(carType => carType.Name);

并在页面中选择它:

@Html.DropDownListFor(model => model.Type, new SelectList(ViewBag.Types, "Value", "Key"))

但是在POST方法中,我总是在Car属性中使用null构造Type对象。

[HttpPost]
public ActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
        _context.Cars.Add(car);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(car);
}

是否可以使用DropDownList选择自定义对象?因为选择intstring等值可以正常工作。

我有一个想法是使用int ID而不是CarType编写ViewModel,并在保存到数据库之前找到Type by ID。但是这样我需要将所有Car属性及其属性复制到我的ViewModel,最后将所有值复制到新的Car对象。对于小班级来说也许没关系,但是对于一些更复杂的 - 不要这么认为......

这是一个小例子。解决此类问题的常用方法是什么?如何编写灵活简单的代码?

1 个答案:

答案 0 :(得分:1)

这是我用于这些场合的可靠的HtmlHelper扩展方法:

public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, SelectListItem initialItem)
    where TProperty : struct
{
    if (!typeof(TProperty).IsEnum)
        throw new ArgumentException("An Enumeration type is required.", "enum");

    IList<SelectListItem> items = Enum.GetValues(typeof(TProperty)).Cast<TProperty>()
            .Select(t => new SelectListItem { Text = (t as Enum).GetDescription(), Value = t.ToString() }).ToList();

    if (initialItem != null)
        items.Insert(0, initialItem);

    return SelectExtensions.DropDownListFor<TModel, TProperty>(helper, expression, items, null, null);
}

这将允许您编写如下代码:

@Html.DropDownListForEnum(model => model.Type)

并为您提供一个完全填充的选择元素,并选择传入Type

上述方法可以使用htmlAttributes以及其他任何内容进行扩展,但这是一个好的开始

相关问题