Render ASP.NET MVC PartialView with Model

Render ASP.NET MVC PartialView with Model

This article explains how you can render partial view in main view with model data.

You can render Partial View using Html.RenderAction and Html.RenderPartial helper methods.

 

Create a new ASP.NET MVC application with nameRenderPartialViewWithModel or other name which you like. You may use basic or MVC template to create new application. You may follow steps from getting started tutorial with ASP.NET MVC.

Follow below steps to use Partial View with Model

  1. Add Model

    In this step you will create two models with name Order andOrderLineItem. Order will be used for parent view and OrderLineItem will be used for Partial View.

    Right click on Models folder and add two classes to it with nameOrder and OrderLineItem.

    OrderLineItem Model

    Order Model

    Notice that in Order model we have added IEnumerable<OrderLineItem> which will add multiple rows of OrderLineItem to one Order row. For more details see example of model binding.

  2. Add Controller

    Add a controller with name OrderController. In OrderController you will add a Action Method which returns Order model with data to View.

    Add Index action method in OrderController with below code.

    We have use Order ViewModel with required data. Order contains details of OrderLineItems.

  3. Add PartialView

    Right click on Views -> Shared and select Add View.

    In Add View dialog box give name _orderDetailsWithModel, select check box for Create as Partial View and click Ok.

     

    Open _orderDetailsWithModel.cshtml and add below HTML code to it.

  4. Add Order View

    In this step you will add a View with name Index. Use _orderDetailsWithModel partial view to display OrderLineItems.

    Create view in Views -> Order folder. Name it Index. Add below HTML code to index.cshtml.

You can also use independent OrderLineItem model with Partial View.

Add below child action in OrderController.

Notice that it uses only OrderLineItem model independently.

Call Child action from view. Use below code for this. For more ways to render partial views in mvc.

Now navigate to http://localhost:64556/order/index it generates below output.

To view or add a comment, sign in

More articles by Manisha Kadam

  • Cross Apply And Outer Apply With Examples

    This article describes about Cross Apply and Outer Apply and give some examples with functions. The Apply operator…

Others also viewed

Explore content categories