I have two view models:
public class ParentViewModel
{
public Id { get; set; }
.....
public ChildViewModel Child{ get; set; }
}
public class ChildViewModel
{
public ChildId { get; set; }
.....
}
Controllers:
public ActionResult Index()
{
.... <some code>
return View("NewIndex", ParentViewModel);
}
[HttpPost]
public ActionResult PartialAction(ChildViewModel childView)
{
return RedirectToAction("Index");
}
And views: Index
@model ParentViewModel
....
@Html.Partial("_Partial", Model.Child)
and _Partial
@model ChildViewModel
... do some stuff with child model
When I'm trying to open Index page I've got an error:
The model item passed into the dictionary is of type 'ParentViewModel', but this dictionary requires a model item of type 'ChildViewModel'.
Why it tries to pass ParentViewModel instead of ChildViewModel. What I'm doing wrong?
You could return
PartialView("...")
from aController
instead, and call the action from the Index view.Controllers:
And Index
Alternatively, you could initialize ParentViewModel in the
Index()
public ActionResult Index()I had the same issue as the OP. From one of the comments, I realized that the second parameter shouldn't be null, i.e from
If Model.Child is null, then Model is passed instead of Model.Child. If there will be cases when the second parameter is null, then you will have to check first in your code and maybe pass an initialized Child as the second parameter. Something like this
The answer is that needs to pass an empty object to Partial, like