Yos
Yos

Reputation: 493

MVC Partial Views

I am trying to reuse some code and a partial view seems to be the best way to do this when using MVC.

I have created a partial view (see below) which inherits from IEnumerable.

@model IEnumerable<Models.facility>

<div class="display-field">
    @foreach (var facility in Model)
    {
        <li>
            @facility.name
        </li>
    }
</div>

The view that embeds this view does it like so:

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

Error:

Object reference not set to an instance of an object.

Can somebody advise me whether I am doing the correct thing and where I am going wrong other than the fact it is null?

Upvotes: 3

Views: 604

Answers (3)

Force444
Force444

Reputation: 3381

When you're invoking @{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're getting the null reference error because when the view is being rendered it is trying to access the model which you have declared in the view as:

@model IEnumerable<Models.facility>

If you change the invoking line to @{Html.RenderPartial("FacilityPartial", model);} it should work. The view can now act on the model which is being passed into it.


As a side note, the accepted answer by @Jobbert Enamno, uses @Html.Partial as opposed to @Html.RenderPartial which you have used in your question. the difference between these may be confusing you or anyone else viewing this question:

@Html.Partial returns the rendered view as a MvcHtmlString, so you could store this in a variable if you wanted.

@Html.RenderPartial does not return anything i.e. void, and thus outputs straight to the Response stream.

Performance-wise it is generally better to use the latter. See this question for more detailed answers.

Upvotes: 0

Artless
Artless

Reputation: 4568

You forgot to pass a parameter to your partial view, thus the null reference. Should be:

@{Html.RenderPartial("FacilityPartial", someIEnumerableVariableHere);} 

Upvotes: 2

Jobert Enamno
Jobert Enamno

Reputation: 4461

Use Html.Partial. 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:

enter image description here

Upvotes: 3

Related Questions