SB2055 SB2055 - 1 month ago 19
C# Question

Multiple Partial Views need the same Model - Only one 'model' statement is allowed in a file

In my view I have this:

@Html.Partial("_MyView.Subsection1", Model)

@Html.Partial("_MyView.Subsection2", Model)


But I get an error -
Only one 'model' statement is allowed in a file.


How can I go about supporting my
Model
in multiple partial views?

Answer

I think you are placing two model statements in your file like following:

@model Model1
@model Model2

This is not allowed, but you can merge both models into a single Model with two properties as follow:

public class MergedModel
{
 public Model1 FirstModel {get;set;}
 public Model2 SecondModel {get;set;}
}

So this way you can pass them to corresponding partial views:

@model MergedModel

@Html.Partial("_MyView.Subsection1", Model.FirstModel)
@Html.Partial("_MyView.Subsection2", Model.SecondModel)