1

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:)

2
  • You are not passing a model to Html.Partial, so the Model is null in Notes.cshtml Commented Oct 24, 2015 at 19:36
  • Its still giving a null. Could you possibly give an example please? Commented Oct 24, 2015 at 19:47

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.