Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass model to partial view

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?

like image 720
DarkNik Avatar asked Jan 16 '14 20:01

DarkNik


People also ask

How do you send model data to partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.

Can we use model in partial view?

Partial Views can use the Page Model for their data whereas Child Actions use independent data from the Controller. Editor/Display templates pass items from the model to the system but can be overridden by user partial views.

How do you implement partial view?

To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.


2 Answers

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

@model ParentViewModel @Html.Partial("_Partial", Model.Child) 

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

@Html.Partial("_Partial", new Child()) 
like image 189
Dev Avatar answered Oct 05 '22 02:10

Dev


The answer is that needs to pass an empty object to Partial, like

@Html.Partial("_Partial", new ChildViewModel ()) 
like image 29
DarkNik Avatar answered Oct 05 '22 01:10

DarkNik