Asp.net mvc 3 在asp.net mvc 3中实现dropdownlist
我正在自学asp.NETMVC3。我做了很多研究,但是我读得越多,我就越困惑。我想创建一个页面,用户可以注册他们的财产出售或出租 我创建了一个如下所示的数据库:Asp.net mvc 3 在asp.net mvc 3中实现dropdownlist,asp.net-mvc-3,html.dropdownlistfor,Asp.net Mvc 3,Html.dropdownlistfor,我正在自学asp.NETMVC3。我做了很多研究,但是我读得越多,我就越困惑。我想创建一个页面,用户可以注册他们的财产出售或出租 我创建了一个如下所示的数据库: public class Property { public int PropertyId { get; set; } public int PropertyType { get; set; } ··· public int Furnished { get; set
public class Property
{
public int PropertyId { get; set; }
public int PropertyType { get; set; }
···
public int Furnished { get; set; }
...
}
现在,我想要dropdownlistfor=PropertyType并提供
属性类型将是
一套
2号楼
3独立式住宅
将提供:
1家具
2无家具
3件家具
现在,我真的不知道在我的代码中应该把这些信息保存在哪里。我的数据库中是否应该有两个存储此查找的表?或者我应该有一个包含所有查找的表?或者我应该把这些信息保存在模型中吗
模型将如何绑定到PropertyType并在Property实体中提供
谢谢 我通常通过在代码中使用枚举来处理这种情况:
public enum PropertyType {
Flat = 1,
House = 2,
Detached House = 3
}
那么在你看来,
<select>
@foreach(var val in Enum.GetNames(typeof(PropertyType)){
<option>val</option>
}
</select>
@foreach(Enum.GetNames中的var val(typeof(PropertyType)){
瓦尔
}
您可以将选项的id设置为等于枚举中每个项的值,并将其传递给控制器
编辑:直接回答您的问题:
您可以将它们存储为数据库中的查找,但对于不太可能改变的小问题,我通常只使用枚举,并节省往返时间
还可以看看这种方法,因为它看起来比我的好:
通过在数据库中存储属性类型和提供的类型,您可以使用外键强制执行数据完整性,而不仅仅是存储整数id,因此我绝对推荐这样做 这也意味着,如果您想添加新类型,它是经过未来验证的。我知道值不会经常更改/永远不会更改,但如果您想在将来添加平房/maisonette,您不必重建和部署项目,只需在数据库中添加新行即可 就如何工作而言,我建议使用传递到视图的ViewModel,而不是直接传递数据库模型。这样可以将数据库模型与视图分开,视图只看到它需要的内容。这还意味着下拉列表等是强类型的,直接位于视图模型中,而不是n刚刚扔进ViewBag。您的视图模型可能如下所示:
public class PropertyViewModel
{
public int PropertyId { get; set; }
public int PropertyType { get; set; }
public IEnumerable<SelectListItem> PropertyTypes { get; set; }
public int Furnished { get; set; }
public IEnumerable<SelectListItem> FurnishedTypes { get; set; }
}
public class PropertiesController : Controller
{
[HttpGet]
public ViewResult Edit(int id)
{
Property property = db.Properties.Single(p => p.Id == id);
PropertyViewModel viewModel = new PropertyViewModel
{
PropertyId = property.Id,
PropertyType = property.PropertyType,
PropertyTypes = from p in db.PropertyTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.PropertyTypeId.ToString()
}
Furnished = property.Furnished,
FurnishedTypes = from p in db.FurnishedTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.FurnishedTypeId.ToString()
}
};
return View();
}
[HttpGet]
public ViewResult Edit(int id, PropertyViewModel propertyViewModel)
{
if(ModelState.IsValid)
{
// TODO: Store stuff in the database here
}
// TODO: Repopulate the view model drop lists here e.g.:
propertyViewModel.FurnishedTypes = from p in db.FurnishedTypes
orderby p.TypeName
select new SelectListItem
{
Text = p.TypeName,
Value = g.FurnishedTypeId.ToString()
};
return View(propertyViewModel);
}
}
你的观点是:
@Html.LabelFor(m => m.PropertyType)
@Html.DropDownListFor(m => m.PropertyType, Model.PropertyTypes)