加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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(例如注入类型构造函数).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读