jonas
jonas

Reputation: 994

Access model from shared partial view independent of controller

I'm creating a simple webpage in asp.net mvc 3.

I have a sidebar that loads random citations, and the sidebar is on every page so it's a part of the layout, independent of the controller.

What is the correct way to access a datamodel from that view? Do I have to pass data from each controller?

My partial view file looks something like:

@model MvcApplication1.Models.CitationModel
@Model.Citation

But this results in a null reference.

The model is something like

   public class CitationModel
{
    public string Citation{ get { return "Test"; } }
}

Upvotes: 1

Views: 970

Answers (3)

danludwig
danludwig

Reputation: 47375

I would do this with a child action. This way you can keep the view strongly typed (no viewbag or viewdata), without having to put it in a "master" viewmodel that gets sent to your layout:

<div id="sidebar">
    @Html.Action("RandomCitations", "Citations")
</div>

In CitationsController:

[ChildActionOnly]
public PartialViewResult RandomCitations()
{
    var model = new CitationModel();
    // populate model
    return PartialView(model);
}

Your view will stay the same, and will be injected into the sidebar div for every layout.

Upvotes: 7

robasta
robasta

Reputation: 4701

I'd use a base controller class like this:

public class ApplicationController : Controller
    {
        public ApplicationController()
        {
           Citation c = getYourCitation();

           ViewBag.Citation = c;
        }
}

Get all your controllers to inherit from Application controller

public class HomeController : ApplicationController
    {
       //Controller code
    }

Each view (including _Layout) will then be able to access the ViewBag

in _Layout.cshtml do this:

@Html.Partial("_CitationPartial", (Your.MidTier.Models.Citation)ViewBag.Citation)

Upvotes: 0

Ph0en1x
Ph0en1x

Reputation: 10067

There are plenty of scenarios there. For now for that cases I put model to view bag, and then getting it from viewbag on view.

Upvotes: 0

Related Questions