jessegavin
jessegavin

Reputation: 75650

Partial view using a ViewModel which inherits from another class doesn't work

I have a view model for a view which displays multiple forms on the same page. This view model contains 'sub-view-models' for each form that will be rendered. Each form has it's own PartialView.

All of these forms share a set of properties (contact info), yet each form has a distinct set of additional properties. So I thought it made sense for each of these form classes to inherit from a base class. However, when I attempt to access the url, I get the following error.

The model item passed into the dictionary is of type 'MyProject.ViewModels.JobForm', but this dictionary requires a model item of type 'MyProject.ViewModels.NightShiftForm'.

Main View

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

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

Partial View for '_NightShiftForm'

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

View Model & Form Classes

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; }
}

Does anyone know why this might be happening?

Upvotes: 1

Views: 1365

Answers (1)

jessegavin
jessegavin

Reputation: 75650

Turns out that MVC has a hard time when you pass null values as the model parameter to Html.RenderPartial. My fix looks like the following:

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

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

Upvotes: 3

Related Questions