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

x
  • 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>
<table>
    <tr>
        <th>
            ProductDescription
        </th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ProductDescription)
        </td>
    </tr>
}
</table>

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) {
            $('div#right-box.data').html(data);
        });
    }
            </script>
<h2>@ViewBag.Message</h2>
<input type="button" value="Show Products" onclick="getProducts()" />
 <div id="right-box" class="data" style="visibility:visible;">
                   @* Section to display partial forms *@
                </div>

I click the "Show Products" button, it calls my function just fine:
[HttpGet]
        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?
0
troycomp
Asked:
troycomp
1 Solution
 
Marcin_ZawadzkiCommented:
Model is just in View a Type definition.
So you have to populate model in ShowProduct, and pass it to View:


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

0
 
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
0

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