Can a _Layout.cshtml have a controller

Refresh

5 days ago

Views

6 time

0

I want to add navigation from database in _Layout.cshtml. I've created a controller for this and create _Layout.cshtml as a list view but its not working

This is my view code

@model IEnumerable<ITM_College.Models.field_tbl>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<nav>
<ul>
            @foreach (var item in Model)
            {
                <li> @Html.DisplayFor(modelItem => item.Field_Name)</li>

            }
        </ul>
</nav>

Controller code

public class SharedController : Controller
{
    ITMCollegeEntities db = new ITMCollegeEntities();
    // GET: Shared
    [ChildActionOnly]
    public ActionResult _Layout()
    {
        var li = db.field_tbl.ToList();
        return View(li);
    }
}

1 answers

0

Нет, но есть различные способы ее решения:

1) Создать базовый класс контроллера или другой инструмент класс, который содержит некоторые общие Utilites, которые должны совместно между контроллерами.

2) PartialView и Html.RenderAction

[ChildActionOnly]
public ActionResult Something(string p)
{
    var entities = repository.GetEntities(p);
    var partialViewModel = new PartialViewModel(entities);
    return PartialView(partialViewModel); 
}