user1166905
user1166905

Reputation: 2622

ASP.Net MVC Partial View Model Binding

I'm very new to MVC and I am looking to put a list of links on the main layout(master page) based on database table. I'm sure I read before that you shouldn't try to load models on the master page but use Partial Views instead (correct me if I'm wrong).

I've looked on Google and on other questions here but they only seem to talk about passing data from a main view to a partial view via ViewBag but I think I just want to add a partial view that I can add to the master page.

Can someone please tell me how to create a partial view I can add to master page so its used on every page and be able to load the list of links required i.e. by binding IEnumerable model to Partial View?

Upvotes: 0

Views: 1191

Answers (1)

Ant P
Ant P

Reputation: 25231

Try using ChildActionExtensions.Action

In your layout:

@Html.Action("MyAction", "MyController")

Controller:

public ActionResult MyAction()
{
    var list = // get your list values 
    return PartialView("MyViewName", list);
}

Then just create your partial view:

@model IEnumerable<WhateverType>

@* View goodness *@

You can use this to bind whatever model you need to your partial view and if you use the Action helper in your Layout.cshtml it'll be rendered on every page.

Upvotes: 3

Related Questions