【问题标题】:Partial view using a ViewModel which inherits from another class doesn't work使用从另一个类继承的 ViewModel 的部分视图不起作用
【发布时间】:2011-09-13 14:53:48
【问题描述】:

我有一个视图模型,用于在同一页面上显示多个表单。此视图模型包含将要呈现的每个表单的“子视图模型”。每个表单都有自己的 PartialView。

所有这些表单都共享一组属性(联系信息),但每个表单都有一组不同的附加属性。所以我认为这些表单类中的每一个都从基类继承是有意义的。但是,当我尝试访问该 url 时,出现以下错误。

传入字典的模型项是类型 'MyProject.ViewModels.JobForm',但是这本字典 需要类型的模型项 'MyProject.ViewModels.NightShiftForm'。

主视图

<%@ Control Language="C#"
  Inherits="ViewUserControl<MyProject.ViewModels.JobsViewModel>" %>

<%: Html.Partial("_NightShiftForm", Model.NightShiftForm) %>
<%: Html.Partial("_DayShiftForm", Model.DayShiftForm) %>

“_NightShiftForm”的部分视图

<%@ Control Language="C#"
  Inherits="ViewUserControl<MyProject.ViewModels.NightShiftForm>" %>

查看模型和表单类

public class JobsViewModel {
  public NightShiftForm NightShiftForm { get; set; }
  public DayShiftForm DayShiftForm { get; set; }
}

public class JobForm {
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

public class DayShiftForm : JobForm {
  public string PreferredCoffeeBrand { get; set; }
  public bool IsMorningPerson { get; set; }
}

public class NightShiftForm : JobForm {
  public string PreferredLocation { get; set; }
  public string PreferredNights { get; set; }
}

有人知道为什么会这样吗?

【问题讨论】:

  • 我怀疑您的JobsViewModel 中的两个属性的类型为JobForm,而不是您在NightShiftFormDayShiftForm 的问题中显示的那样。您在问题中显示的内容应该可以正常工作。

标签: asp.net-mvc inheritance viewmodel partial-views


【解决方案1】:

事实证明,当您将空值作为模型参数传递给 Html.RenderPartial 时,MVC 会遇到困难。我的修复如下所示:

public class JobsViewModel {
  public NightShiftForm NightShiftForm { get; set; }
  public DayShiftForm DayShiftForm { get; set; }

  public JobsViewModel() {
    NightShiftForm = new NightShiftForm();
    DayShiftForm = new DayShiftForm();
  }
}

【讨论】:

  • 是的......我在将空模型传递给RenderPartial()时也遇到了问题...... MVC似乎在寻找父级的类型。这确实是这里的解决方案——确保模型(或子模型)被实例化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
相关资源
最近更新 更多