user2806570
user2806570

Reputation: 859

Partial Views in another Controllers View MVC5

Im new to using partial views in mvc and for some reason could not get this working

Notes.cshtml

@model IEnumerable<SI2.Models.DashboardNote>

@foreach (var item in Model)
{
    <div class="col-lg-12">
        <div class="well">
            <p>@Html.DisplayFor(modelItem => item.Information)</p><br />
            <p>@Html.DisplayFor(modelItem => item.DateCreate)</p>
        </div>
    </div>
}

This is where I'm trying to call the partial view in another controllers view

Home/Index.cshtml

<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading"><i class="fa fc-agenda-view"></i>   Notes</div>
            <div class="panel-body">
                @Html.Partial("~/Views/DashboardNotes/Notes.cshtml")
            </div>
        </div>
    </div>
</div>

Notes controller

public ActionResult Notes()
{
     return View(db.DashboardNotes.ToList());
}

Every time I try calling Notes.cshtml as a partial view I receive a System.NullReferenceException with "Object reference not set to an instance of an object" but if I run the view normally it runs perfectly. There is no relation between the two models of the controllers either.

Thanks for any help:)

Upvotes: 1

Views: 872

Answers (1)

Ross Bush
Ross Bush

Reputation: 15175

The code below will render your partial with no notes, hence the null reference, because you have a foreach for null notes.

@Html.Partial("~/Views/DashboardNotes/Notes.cshtml")

There is no mechanism in Html.Partial that triggers a call to the server. You would have to do some type of ajax call in your partial to get notes if you load it in the manner you are now. The easiest way to go about this is to return the Notes in your parent view or page and pass in the model to your partial, see below:

@model MainViewWithNotes

<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading"><i class="fa fc-agenda-view"></i>   Notes</div>
            <div class="panel-body">
                @Html.Partial("~/Views/DashboardNotes/Notes.cshtml",MainViewWithNotes.Notes)
            </div>
        </div>
    </div>
</div>

Upvotes: 3

Related Questions