asp.net-mvc – 带接口的ASP.NET MVC UpdateModel
发布时间:2020-12-16 03:46:37 所属栏目:asp.Net 来源:网络整理
导读:我试图让UpdateModel填充一个在编译时设置为只有接口的模型.例如,我有: // View Modelpublic class AccountViewModel { public string Email { get; set; } public IProfile Profile { get; set; }}// Interfacepublic interface IProfile { // Empty}// Ac
我试图让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,它在重写的CreateModel方法中使用StandardProfile实例填充IProfile. 问题是从不填充FavoriteFood和FavoriteMusic.有任何想法吗?理想情况下,这一切都将在模型绑定器中完成,但我不确定如果不编写完全自定义的实现. 谢谢,Brian 解决方法
我将不得不检查ASP.NET MVC代码(DefaultModelBinder),但我猜它反映的是IProfile类型,而不是实例,StandardProfile.
所以它寻找它可以尝试绑定的任何IProfile成员,但它是一个空接口,因此它认为自己完成了. 您可以尝试更新BindingContext并将ModelType更改为StandardProfile然后调用 bindingContext.ModelType = typeof(StandardProfile); IProfile profile = base.BindModel(controllerContext,bindingContext); 无论如何,有一个空的接口很奇怪? 编辑:只想添加上面的代码只是伪代码,您需要检查DefaultModelBinder以查看您要编写的内容. 编辑#2: 你可以做: public class ProfileModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext) { { bindingContext.ModelType = typeof(StandardProfile); return base.BindModel(controllerContext,bindingContext); } } 无需为AccountView创建模型绑定器,一个工作正常. 编辑#3 测试出来,上面的活页夹工作,只需要添加: ModelBinders.Binders[typeof(IProfile)] = new ProfileModelBinder(); 你的行动如下: public ActionResult AddAccount(AccountViewModel viewModel) { // viewModel is fully populated,including profile,don't call UpdateModel } 设置模型绑定器时可以使用IOC(例如注入类型构造函数). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – <%#Eval(“State”)%>或<%#DataBin
- asp.net-mvc – TextBoxFor中限制为2位小数
- 什么是Asp.net中的中等信任?
- asp.net-web-api – 在WebApi和MVC项目之间共享SignalR集线
- asp-classic – 在经典ASP中本地化记录集中的日期
- asp.net-mvc – MVC 3 – 在视图中显示字典值
- asp.net – 如何使这个更好的代码和更优化
- asp.net-mvc – 如何在MVC3中为多行文本框创建多个编辑器模
- asp.net-mvc – AppDomain.GetAssemblies和BuildManager.Ge
- ASP.NET – 在Page_Pre_init()或Page_Init()或Page_Load()中
推荐文章
站长推荐
- 更改ASP.NET XHTML渲染模式
- 如何使用Active Directory使用ASP.NET 4.0构建基
- asp.net – 如何在codebehind中调用Eval?
- asp.net-mvc – 使用城堡温莎的实体框架
- asp.net-mvc-3 – .NET MVC 3自定义十进制?模型
- asp.net-mvc-3 – 如何在Razor视图引擎中注册程序
- asp.net-mvc-4 – 捆绑从CDN提供的多个CSS?
- ASP.NET MVC与Web客户端软件工厂(WCSF)
- asp.net-mvc – System.Web.Optimization使函数参
- asp.net-mvc – DDay iCal – 添加一个与会者
热点阅读