Pass ViewBag to _Layout

2

I need to pass a list to my layout where it is used on all my pages, would you like to know how I could do this?

    
asked by anonymous 11.06.2015 / 15:20

3 answers

4

If the code is used on all pages, it is possibly a layout or a dynamic menu. Do not use Session for this .

I'll go through a list of steps to create a dynamic menu.

1. Create a common Controller

Create a file named Controller.cs in the Controllers directory of your project with the following:

public abstract class Controller : System.Web.Mvc.Controller
{

}

This ensures that all your Controllers in your application are derived from it.

2. Create Actions with the Attribute [ChildActionOnly]

Attribute ensures that Action can only be called by another, and never directly.

Example:

public abstract class Controller : System.Web.Mvc.Controller
{
    ...
    [ChildActionOnly]
    public ActionResult Menu()
    {
        var menu = contexto.EntidadeDoMenu.ToList();

        return PartialView(menu);
    }
    ...
}

3. Create a View for each Action created in the Controller in the%

An example (file Views\Shared ):

@model IEnumerable<MeuProjeto.Models.ItemDeMenu>

<ul>
    @foreach (var itemDeMenu in Model) { 
       <li>@Html.ActionLink(itemDeMenu.Nome, "Detalhes", "UmControllerQualquer", new { id = itemDeMenu.Id }, null)</li>
    }
</ul>

4. Make Views\Shared\Menu.cshtml call Action

This step is optional. You can make another component call Action .

@Html.Action("Menu")
    
14.06.2015 / 01:22
0

I think it's more or less what you want:

List<SelectListItem> listItem = new List<SelectListItem>();
List<SeuModel> listModel = repositorio.BuscarDados();

foreach(var item in listModel)
{
   listItem.Add({
      Text: item.Descricao,
      Value: item.Id
   });
}

ViewBag.seuDropDownList = listItem;

I'm sorry if there are any errors in the code, I do not have the dlls and components to test.

    
11.06.2015 / 21:32
0

@Gigano should probably know a better solution, but the only thing I thought was to add in Session itself, eg:

var selectList = new SelectList (suaLista, "ID", "Texto");
Session.Add("meudropdown", selectList);

And in _Layout

@Html.DropDownList("meudrop", Session["meudropdown"] as SelectList)
    
13.06.2015 / 04:00