I have a main model and a partial view. The model for the partial view is a new model with no values. But now I want to pass one element of parent model to the partial view. How do I go about it?
The parent and the partial views have different properties, so I cant use the same model.
Models:
public class Parent
{
.
.
public List<SelectListItem> TypeList { get; set; }
.
.
}
public class Partial1
{
public List<SelectListItem> TypeList1 { get; set; }
.
.
}
public class Partial2
{
public List<SelectListItem> TypeList2 { get; set; }
.
.
}
Parent View:
@model Models.Parent
@Html.Partial("_Partial1", new Partial1())
@Html.Partial("_Partial2", new Partial2())
I realize I can pass it to the partial view using a ViewDataDictionary
and use it, but I was wondering if I could assign it to my partial view model directly. Can I do something like this?
@Html.Partial("_Partial1", new Partial1(new{TypeList1 =Model.TypeList}))
The above code gives a compile time error saying Partial1 does not contain a constructor that takes 1 argument.
EDIT 1:
According to Chris Pratt's answer I modified my code to
@Html.Partial("_Partial1", new Partial1{TypeList1 =Model.TypeList})
This solved the compilation error.But this is now causing a run time error in the partial View 1.
Partial1 View:
@model Models.Partial1
@Html.DropDownListFor(model => model.Type, Model.TypeList1, new { @class = "form-control" })
throws an error "There is no ViewData item of type 'IEnumerable' that has the key 'Type'."