I need to create a view that displays Order Header information and I need to add a patial view that displays a grid of Line Items. The partial view will be strongly typed from a viewmodel. I understand that I should use the html helper @Html.Partial("Path/view"). I have only used controllers up til now to open a view, populating the viewmodel before sending it to the view. Since the partial view is being called form the html helper, I would like to know is what would be the best way to populate the parital view with the model data.
Asp.net-mvc – How to populate mvc razor partial view
asp.net-mvcrazor
Related Topic
- Escape @ character in razor view engine
- Javascript – Using Razor within JavaScript
- Asp.net-mvc – ASP.NET MVC 3 – Partial vs Display Template vs Editor Template
- Asp.net-mvc – Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine
- C# – Using partial views in ASP.net MVC 4
Best Answer
Option 1: Inherit from parent page
By default, any partial view rendered by calling
@Html.Partial("PartialViewName")
will get the view model passed to the parent view.So if you have:
View Model
OrderInfo.cshtml
The OrderLineItems page should get a
MyNamespace.OrderViewModel
passed to it... so your partial view should look like this:OrderLineItems.cshtml
Option 2: Specify model
You can use the second parameter to specify the view model to be passed. I.e.
OrderInfo.cshtml
OrderLineItems.cshtml
Option 3: Use partial actions
If you need to reuse a partial view over multiple pages, it could be a good idea to use a partial view to eliminate having to populate different view models with the same info just because the page is going to be using the same partial.
E.g.
View Model
Controller
OrderInfo.cshtml
OrderLineItems.cshtml