我正在尝试在 MVC 中创建一个 ViewModel,它允许我在显示格式和编辑格式之间切换。
我可以让控制器选择正确版本的 ViewModel,并且在调试器中显示继承类和基类的所有属性。
当 ViewModel 被传递给视图时,只显示继承类的属性。
这种方法可以工作还是我应该创建两个单独的 ViewModel?
视图模型:
public partial class HouseholdViewModel
{
public int Id { get; set; }
public int familyID { get; set; }
public string entityName { get; set; }
public System.DateTime attachmentDate { get; set; }
}
public partial class DisplayHouseholdViewModel : HouseholdViewModel
{
public string phone { get; set; }
}
public partial class CreateHouseholdViewModel : HouseholdViewModel
{
public string familyPhoneCode { get; set; }
public string familyPhone { get; set; }
}
控制器(片段):
public class HouseholdController : Controller
{
private WhatWorksEntities db = new WhatWorksEntities();
//return viewmodel object
private string displayView = "displayView";
private string createView = "createView";
public IEnumerable<object> GetModel(string view)
{
if (view == displayView)
{
var householdView = (from h in db.tHouseholds
select new DisplayHouseholdViewModel
{
Id = h.householdID,
familyID = h.familyID,
entityName = h.tEntity.entityName,
attachmentDate = h.attachmentDate,
phone = h.familyPhoneCode + " " + h.familyPhone
}).AsEnumerable();
return (householdView);
}
else
{
var householdView = (from h in db.tHouseholds
select new CreateHouseholdViewModel
{
Id = h.householdID,
familyID = h.familyID,
entityName = h.tEntity.entityName,
attachmentDate = h.attachmentDate,
familyPhoneCode = h.familyPhoneCode,
familyPhone = h.familyPhone
}).AsEnumerable();
return (householdView);
}
}
//
// GET: /Household/
public ActionResult Index()
{
var householdView = GetModel(displayView).Cast<DisplayHouseholdViewModel>();
return View(householdView);
}
返回的视图不显示电话属性:
---编辑以显示带有电话数据的调试器---
调试视图: