On my contacts list page I want to apply filters without refreshing the whole page. This post is about step one of my first try at accomplishing this goal.
To add a partial view right clicked on the destination folder for the new view and from the Add menu select the View option.
This brings up the Add View dialog. I am adding a view call _ContactList using the list template since this is going to be a list of contact. Contact is the model the list will be based on and any data access will happen via the ContactDbContext. The last thing to do is check the create as a partial view check box. Clicking add creates a _ContactList.cshtml file.
The resulting code in _ConactList.cshtml looks like this:
@model IEnumerable<Contacts.Models.Contact> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Address) </th> <th> @Html.DisplayNameFor(model => model.City) </th> <th> @Html.DisplayNameFor(model => model.State) </th> <th> @Html.DisplayNameFor(model => model.ZipCode) </th> <th> @Html.DisplayNameFor(model => model.Country) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Address) </td> <td> @Html.DisplayFor(modelItem => item.City) </td> <td> @Html.DisplayFor(modelItem => item.State) </td> <td> @Html.DisplayFor(modelItem => item.ZipCode) </td> <td> @Html.DisplayFor(modelItem => item.Country) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </table>
As you can see by choosing the contact model Visual Studio was able to build a view that displays all the properties of the contact. Since I chose the list template the view is expecting a list of contacts that it will iterate over that list and create a table from the list of contacts.
In my index view I was able to remove all the code associated with the contact list and replace it with the following code which renders my new partial view.
@{ Html.RenderPartial("_ContactList"); }
This partial view will allow me to have a consistent view of my contact list any where I may need it. It is also my hope that this partial view will allow me to refresh the list portion of the contact list page when a filter is changed.