ASP.NET call a controller method from the master page?

谁说我不能喝 提交于 2019-12-06 08:05:59

You could use the Html.Action or Html.RenderAction helpers. For example you could put the following somewhere on your master page:

<%= Html.Action("TotalSalesThisMonth", "SomeController") %>

This will execute the controller action, render the view and insert the generated HTML at the specified location in the master page. You could also restrict this action for being used only as child action by decorating it with the [ChildActionOnly] attribute:

[ChildActionOnly]
public ActionResult TotalSalesThisMonth()
{
    var totalSalesModel = SalesService.GetTotalSalesThisMonth()
    return View(totalSalesModel);
}

And finally if inside the controller action you wanted to test whether it was called as a normal action or as a child action you could do this:

public ActionResult TotalSalesThisMonth()
{
    var totalSalesModel = SalesService.GetTotalSalesThisMonth()
    if (ControllerContext.IsChildAction)
    {
        return View("foo", totalSalesModel);
    }
    return View("bar", totalSalesModel);
}
Yoko Zunna

Quoting from http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

I’ll use the term RenderAction to refer to both of these methods. Here’s a quick look at how you might use this method. Suppose you have the following controller.

public class MyController {
  public ActionResult Index() {
    return View();
  }

  [ChildActionOnly]
  public ActionResult Menu() {
    var menu = GetMenuFromSomewhere();
      return PartialView(menu);
  }
}

The Menu action grabs the Menu model and returns a partial view with just the menu.

<%@ Control Inherits="System.Web.Mvc.ViewUserControl<Menu>" %>
<ul>
<% foreach(var item in Model.MenuItem) { %>
  <li><%= item %></li>
<% } %>
</ul>

In your Index.aspx view, you can now call into the Menu action to display the menu:

<%@ Page %>
<html>
<head><title></title></head>
<body>
  <%= Html.Action("Menu") %>
  <h1>Welcome to the Index View</h1>
</body>
</html>

The content above is licensed under CC-BY: http://creativecommons.org/licenses/by/2.5/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!