Pass Data to Partial View – ASP.NET MVC

There are many ways to pass Data to the Partial View. I’ll discuss here method which I use in my projects which is passing Strongly Typed Model to the View.

View Models

public class ParentViewModel
{
	public Id { get; set; }
	.....
	public ChildViewModel Child { get; set; }	
}

public class ChildViewModel
{
	public Id { get; set; }
	.....
}

Controller

public ActionResult Index()
{
	....
	return View("Index", new ParentViewModel());
}

Index View
Render Partial View here and pass it Model.Child

@model ParentViewModel

... use parent model here

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

Partial View

@model ChildViewModel

... use child model here

Make sure Model.Child is not null, if it is null, then Model is passed instead of Model.Child. You should check in your code and pass an initialized Child as the second parameter.

Leave a Reply

Your email address will not be published.