我有一个视图模型,该视图在同一页面上显示多个表单。这个视图模型包含了要呈现的每个表单的"子视图模型"。每个表单都有自己的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) %>
局部视图
<%@ 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; }
}
有人知道为什么会发生这种情况吗?
当您将空值作为模型参数传递给Html.RenderPartial
时,MVC很难。我的修复程序如下所示:
public class JobsViewModel {
public NightShiftForm NightShiftForm { get; set; }
public DayShiftForm DayShiftForm { get; set; }
public JobsViewModel() {
NightShiftForm = new NightShiftForm();
DayShiftForm = new DayShiftForm();
}
}