プロパティタイプと提供されたタイプをデータベースに保存することで、整数IDを保存するだけでなく、外部キーを使用してデータの整合性を強化できるため、これを強くお勧めします。
また、新しいタイプを追加したい場合に備えて、将来にわたって利用できることも意味します。値は頻繁に変更されない/変更されないことはわかっていますが、将来バンガロー/メゾネットを追加したい場合は、プロジェクトを再構築してデプロイする必要はなく、データベースに新しい行を追加するだけです。
これがどのように機能するかという点では、データベースモデルを直接渡すのではなく、ビューに渡されるViewModelを使用することをお勧めします。このようにして、データベースモデルをビューから分離すると、ビューには必要なものだけが表示されます。また、ドロップダウンリストなどが強く型付けされており、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)