Partial views of MVC
I am trying to reuse some code and Partial View seems to be the best way to do it when using MVC.
I've created a partial view (see below) that inherits from IEnumerable.
@model IEnumerable<Models.facility>
<div class="display-field">
@foreach (var facility in Model)
{
<li>
@facility.name
</li>
}
</div>
The view that inserts this view looks like this:
<div class="display-field">
<div> @{Html.RenderPartial("FacilityPartial");} </div>
</div>
So now the problem.
I am getting a null reference error and I can see that the Model variable is null.
Mistake:
An object reference is not set on an object instance.
Can anyone advise me if I am doing the right thing and where am I going wrong other than the fact that it is null?
source to share
Use Html.Partial. Let's consider this example.
Index view (Home)
@{
ViewBag.Title = "Home Page";
//Test model to be passed to the partial view
var products = new List<Product> { new Product{ProductName="Test product 1", ProductId=1234}};
}
@Html.Partial("_TestPV", products)
_TestPV (partial view)
@model IEnumerable<Product>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
ProductName
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
</tr>
}
</table>
Output:
source to share
When you call @{Html.RenderPartial("FacilityPartial");}
, you provided the name of the partial view, but you forgot to include the model as a parameter. This is why you are getting a null pivot error because when the view is rendered, it tries to access the model you specified in the view like:
@model IEnumerable<Models.facility>
If you change the calling string to @{Html.RenderPartial("FacilityPartial", model);}
, it should work. Now the view can act on the model that is passed to it.
As a side note, the accepted answer by @Jobbert Enamno uses @Html.Partial
as opposed to the @Html.RenderPartial
one you used in your question. the difference between the two might confuse you or anyone else considering this:
@Html.Partial
returns the rendered view as MvcHtmlString
, so you can store it in a variable if you like.
@Html.RenderPartial
returns nothing, i.e. void, and therefore outputs directly to the stream Response
.
It is better to use the latter effectively. See this question for more detailed answers.
source to share