通常,当我创建 MVC 视图时,我首先将我的视图绑定到一个,ExpandoObject
这样我就可以快速找出我的视图模型的形状,而不必花时间在强类型视图模型中添加/修改/删除真实属性。
但是一旦我对我的视图模型应该是什么样子有了很好的感觉,我更愿意为它创建一个实际的类。如果我可以从 ExpandoObject 自动生成视图模型,那就太好了。那可能吗?
public virtual ActionResult DoStuff(int stuffId)
{
// eventually this stuff gets moved to a service class
dynamic vm = new ExpandoObject();
using (var ctx = new MyContext())
{
vm.Stuff = ctx.Stuff
.Where(x => x.Id == stuffId)
.Select(x => new
{
Foo = x.Foo,
Bar = x.Bar
}).SingleOrDefault().ToExpando();
}
// once I know what vm looks like, I'll want to do this to easily create a new class
// string stronglyType = GenerateStronglyTypeClass(vm);
return View(vm);
}
public string GenerateStronglyTypedClass(ExpandoObject object)
{
// what goes here??
}