按照NerdDinners示例,我有兴趣创建一个强类型的母版页。为了实现这一点,我使用了一个基本控制器来检索母版页的数据。所有其他控制器都继承这个类。同样,我有ViewModels
母版页和任何其他视图。视图ViewModel
类继承自母版页的ViewModel
.
问题
子控制器应如何确保将母版页的数据传递给视图而不设置ViewModel
与母版页本身相关的属性?
我的母版页将显示许多按钮,这些按钮在 XML 文件中确定,因此Buttons
是我要填充的类。
MasterPage ViewModel 代码片段
using System.Collections.Generic;
namespace Site1.Models
{
public class MasterViewModel
{
public List<Button> Buttons{set; get;}
}
}
看法ViewModel
namespace Site1.Models
{
public class View1ViewModel : MasterViewModel
{
public SomeDataClass SomeData { get; set; }
}
}
基本控制器
using System.Collections.Generic;
using System.Web.Mvc;
using Site1.Models;
namespace Site1.Controllers
{
public abstract class BaseController : Controller
{
protected MasterViewModel model = new MasterViewModel();
public BaseController()
{
model.Buttons = new List<Button>();
//populate the button classes (doesn't matter how)
PopulateButtons(model.Buttons);
}
}
}
视图的控制器:
using System.Web.Mvc;
namespace Site1.Controllers
{
public class View1Controller : BaseController
{
public ActionResult Index()
{
Models.View1ViewModel viewModel = new Models.View1ViewModel();
SomeDataClass viewData = new SomeDataClass()
//populate data class (doesn't matter how)
PopulateDataClass(viewData);
viewModel.SomeData = viewData;
//I WANT TO ELIMINATE THE FOLLOWING LINE!
viewModel.Buttons = model.Buttons;
return View("Index", viewModel);
}
}
}
母版页继承System.Web.Mvc.ViewMasterPage<Site1.Models.MasterViewModel>
.
视图继承System.Web.Mvc.ViewMasterPage<Site1.Models.View1ViewModel>
.