2011-08-17 53 views
1

我有一个型号(简体):ASP.NET MVC中选择值从下拉列表

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 in Type property。

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

    return View(car); 
} 

是否有可能选择与DropDownList的自定义对象?因为选择值如int,string工作正常。

我有一个想法,使用int ID而不是CarType来编写ViewModel,并在保存到数据库之前找到按ID的类型。但这种方式,我需要复制所有Car特性以及与我的视图模型,并在最后的属性 - 所有的值复制到新的Car对象。小班它也许还行,但对于一些比较复杂的 - 不这么认为......

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

回答

1

这里有一个值得信赖的HtmlHelper扩展方法我用这些occassions:

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扩展和任何其他,但它是一个良好的开端

+0

我是否正确地理解,这helper方法只是构建SelectListItem'的'名单,填补其'Text'和'价值'属性并为我的属性创建'DropDownListFor'?问题是'Value'是一个字符串。所以这种方法将默认返回非空的CarType对象(0代表int)。当我需要使用来自数据库的Id的CarType对象时。 –

+0

我看到你使用了一个'CarType'枚举,所以它是有道理的。你Enum映射到你的数据库表吗?您仍然应该能够将该枚举强制保存为int。 – hunter