2011-08-17 76 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