Huda Noor
Huda Noor

Reputation: 103

Displaying partial page within a View page

I have a Controller/ShoppingCart which has a Action Method Index() and I created a Index View Page which is strongly type and uses a model class

Project.Models.ShoppingCartViewModel

I have an another Controller/Details which has an Action Method Confirm() and I created a Confirm View Page which is also a strongly type and uses a model class

Project.Models.Confirm

Now all I want to do is that Create a Partial View of Index() which will use a @model Project.Models.ShoppingCartViewModel and display this partial page on right side of Confirm View Page. Both are strongly typed view.

Upvotes: 0

Views: 61

Answers (1)

Shyju
Shyju

Reputation: 218852

You should add a new property to Confirm view model of type ShoppingCartViewModel

public class Confirm
{
   public  ShoppingCartViewModel Cart {set;get;}
   //Other Properties of your viewmodel goes here
}

Now in the Confirm view, Call the Html.Partial helper method to render the Partial view which displays shopping cart and pass the Model.Cart property.

@model Project.Models.Confirm
<h2>Confirm order</h2>
@Html.Partial("~/Views/ShoppingCart/_CartPartial.cshtml".Model.Cart)

Assuming your partial view is located at ~/Views/ShoppingCart/_CartPartial.cshtml location.

Make sure you properly initialize the Cart property to avoid Null Reference exception (Object reference not set to an instance of object)

public ActionResult Confirm()
{
  var vm = new Confirm();
  vm.Cart= new ShoppingCartViewModel();
  // Load the Shopping cart property values to vm.Cart
  return View(vm);
}

Upvotes: 1

Related Questions