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
对象。小班它也许还行,但对于一些比较复杂的 - 不这么认为......
这是一个小例子。解决这些问题的常用方法是什么?如何编写灵活简单的代码?
我是否正确地理解,这helper方法只是构建SelectListItem'的'名单,填补其'Text'和'价值'属性并为我的属性创建'DropDownListFor'?问题是'Value'是一个字符串。所以这种方法将默认返回非空的CarType对象(0代表int)。当我需要使用来自数据库的Id的CarType对象时。 –
我看到你使用了一个'CarType'枚举,所以它是有道理的。你Enum映射到你的数据库表吗?您仍然应该能够将该枚举强制保存为int。 – hunter