的ASP.NET MVC UpdateModel我想让UpdateModel填充一个在编译时只被设置为一个接口的模型。例如,我有:带有接口
// View Model
public class AccountViewModel {
public string Email { get; set; }
public IProfile Profile { get; set; }
}
// Interface
public interface IProfile {
// Empty
}
// Actual profile instance used
public class StandardProfile : IProfile {
public string FavoriteFood { get; set; }
public string FavoriteMusic { get; set; }
}
// Controller action
public ActionResult AddAccount(AccountViewModel viewModel) {
// viewModel is populated already
UpdateModel(viewModel.Profile, "Profile"); // This isn't working.
}
// Form
<form ... >
<input name='Email' />
<input name='Profile.FavoriteFood' />
<input name='Profile.FavoriteMusic' />
<button type='submit'></button>
</form>
另外请注意,我有一个从DefaultModelBinder继承使用自定义模型粘合剂用于填充IProfile与在被覆盖的CreateModel方法的StandardProfile的实例。
问题是FavoriteFood和FavoriteMusic从不填充。有任何想法吗?理想情况下,这将全部在模型联编程序中完成,但是我不确定在没有编写完全自定义的实现的情况下是可能的。
感谢布
空的接口允许我在每个站点上重复使用相同的核心代码,同时使用IOC提供不同的配置文件类型。我可能能够尝试一个基类而不是一个接口来达到这个目的,但我只是不确定我还能做什么,这给了我所寻找的灵活性。我会研究你提到的ModelType。 – 2009-09-09 17:35:58
空的基类对你来说也不会有太大的好处。因此,在您的CreateModel方法的代码中,您调用的是如下所示的代码:IoC.GetInstance()您插入了哪个返回新的StandardProfile?有趣的:)。我仍然不清楚当使用IProfile的任何东西必须首先将它转换为正确的类时,您可以获得多少代码重用,但是,我认为在绑定上下文中指定Type将起作用。 –
anonymous
2009-09-09 19:24:39
重复使用来自于我的许多站点的控制器都在我参考的常见组件中。我建立的每个站点都引用了这个用于控制器和模型的公共组件然后,我可以为每个站点添加其他控制器,模型,视图等。在这种情况下,我需要能够逐个网站地定义完全不同的配置文件字段。因此这里只需要一个接口。 – 2009-09-09 19:37:12