[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2619
  • Last Modified:

ASP.NET MVC 3 Partial View Model object is null

I have a created a partial view based off of my ADO.NET entitiy model called ProductList:
@model IEnumerable<MvcPrint.Models.Product>
@foreach (var item in Model) {
            @Html.DisplayFor(modelItem => item.ProductDescription)

The namespace MvcPrint.Models.Product points to a product table in my database.
I want to load it when a button is clicked, Heres my Index.cshtml code on the homecontroller:
    ViewBag.Title = "Home Page";
<script type="text/javascript">
    function getProducts() {
        $.get('/Products/ShowProducts/', function (data) {
<input type="button" value="Show Products" onclick="getProducts()" />
 <div id="right-box" class="data" style="visibility:visible;">
                   @* Section to display partial forms *@

I click the "Show Products" button, it calls my function just fine:
        public ActionResult ShowProducts()
            return PartialView("ProductList");

But the Model is null on the ProductList partial view.
@foreach (var item in Model)

 What am I forgetting to do so the model will return a list of products?
1 Solution
Model is just in View a Type definition.
So you have to populate model in ShowProduct, and pass it to View:

        public ActionResult ShowProducts()
            MvcPrint.Models.Product model = .....//Get a list of product here
            return PartialView("ProductList", model );  //Pass this data to View.

troycompAuthor Commented:
That was it. I thought the view has a life cycle and the code to generate the list of products would be executed when the view was called.

Thank you

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now