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?
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?
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.
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.
[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);
}
...
}
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>
Views\Shared\Menu.cshtml
call Action
This step is optional. You can make another component call Action .
@Html.Action("Menu")
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.
@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)