Calling functions from a controller in the _Layout.cshtml view of ASP.NET MVC5

Asked

Viewed 1,077 times

2

I have a menu being loaded into a controller Action. I’ve already set the view for this action in _Viewstart to be the default for my project. But this view isn’t pulling any comtroller information. I’ve tried for Viewbag, for Model and now I’m trying for Session.

Pages that are configured to be the default Layout, cannot receive controller actions?

Follow my controller:

public class MenuController : Controller
{
    // GET: Menu
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Teste()
    {
        MenuDAO dao = new MenuDAO();
        string usuarioLogado = "diego";
        IList<Menu> menu = dao.MontaMenu(usuarioLogado);

        //ViewBag.Menu = menu;

        Session["teste"] = "Essa frase está vindo do controller";

        return View();
    }
}

Follow my view:

@{
    Layout = null;
}


@model IList<PortalAraguaina.Models.Menu>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Teste</title>
</head>
<body>
    <div>
        Teste
        <p class="essa-eh-a-classe-de-teste">@Session["teste"]</p>
    </div>

    <div>@RenderBody()</div>
  • you can call via javascript

  • but after all.. in the title of the question you talk about calling and in it you talk about pulling.. what do you want to do exactly?

  • I just want the view to load the information that is in the controller action

  • to return your list to the Voce view you have to do this return View(menu);

  • I tried Vinicius, in all views I do so, but in the view I put as default _Layout does not work. Returns null.

  • M. Bertolazo, as you would call via Javascript?

Show 1 more comment

1 answer

1

To render an action result from a view (in your case _Layout), use the Action helper.

You don’t need Viewbag or any other data transport.

Directly return the view html: @Html.Action("Teste", "Menu");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.