This follows on from a previous post, Make sure you have read How to update partial view using jquery ajax before continuing or some of this may not make sense.
In the previous post the partial view was updated when a selection was made from a drop down list. When the main view first loaded there was no code to populate the partial view. The purpose here is to change the original code to allow the partial view to be loaded when the main view is initially loaded.
ViewModels
Create a new view model for the main index view. The CatalogueViewModel contains a DateTime and a list of products. This is the list which will be used to initially populate the partial view.
public class CatalogueViewModel
{
public DateTime CatalogueDate { get; set; }
// any other required properties
public List<Product> Products { get; set; }
}
Main Index View
The main view has changed slightly, As a CatalogueViewModel model is now passed to the view the strongly-typed model declaration needs to change.
@model MVCUpdatePartial.Models.CatalogueViewModel
Also the date displayed is now taken from the view model.
Catalogue Date: @Model.CatalogueDate.ToLongDateString() @Model.CatalogueDate.ToLongTimeString()
The select list for selecting the quantity of products to display now has an additional All option. This is to accommodate the fact that when the view loads initially the quantity is not specified and all products will initially be loaded.
<select id="PageSize">
<option value="">All</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
The div element where the partial view is loaded now has a command to explicitly render the partial view. This will render the view and display a list of products when the main view is initially loaded.
<div id="SelectedProducts">
@{Html.RenderPartial("_ProductList", Model.Products);}
</div>
Controller
The Index (GET) Action method now passes a CatalogueViewModel to the Index view. Initially the products list is populated with all products (OK for this scenario as there are not that many).
Also the GetProducts (POST) Action method handles the situation where a null is passed in the quantity parameter. This will happen when the All option is selected from the select list.
public ActionResult Index()
{
var catalogueVM = new CatalogueViewModel
{
CatalogueDate = DateTime.Now,
Products = products
};
return View(catalogueVM);
}
[HttpPost]
public ActionResult GetProducts(int? quantity)
{
var selectedProducts = products.Take(quantity ?? products.Count);
return PartialView("_ProductList", selectedProducts);
}
Done!





You must be logged in to post a comment.