2

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'."

TheFallenOne
  • 1,598
  • 2
  • 23
  • 57
  • Why not have 2 `List` properties in `Partial1`? – adiga Sep 29 '17 at 18:14
  • Yes, that should work fine. What's the actual issue here? – Chris Pratt Sep 29 '17 at 18:19
  • @ChrisPratt I get a compile time error saying Partial1 does not contain a constructor that takes 1 argument. – TheFallenOne Sep 29 '17 at 18:27
  • @TheFallenOne please completely define what you would like to acheive –  Sep 29 '17 at 18:36
  • 1
    Regarding your edit - It means that `TypeList1` in `Partial1` is `null` (refer [this Q/A](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for more detail) which is presumably because `TypeList` in `Parent` is also `null`) –  Sep 29 '17 at 22:25

2 Answers2

1

Oh sorry. That code actually looked right on first glance, but now I see the issue. You're trying to pass the info as an anonymous object to the constructor, which is parameterless. Instead, you should be using the object initialization syntax:

new Partial1 { TypeList1 = Model.TypeList }
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
-2

try using

@{
    Html.RenderPartial("Partial1", new { param1 = model.property });
}

The MSDN Link.

farzaaaan
  • 410
  • 3
  • 9