ASP.NET调用从主网页的控制器的方法? [英] ASP.NET call a controller method from the master page?

查看:391
本文介绍了ASP.NET调用从主网页的控制器的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC2你怎么骂从主网页的控制器的方法?例如说我想包括在掌握一些概述数据:

In ASP.NET MVC2 how do you call a controller method from the master page? Say for example I wanted to include some overview data in the master:

+--------------------------------------+
| Logo                      Welcome xyz|
+--------------------------------------+
| total sales this month $999          |
+--------------------------------------+
| Home | Sales | Import | Export (menu)|
+--------------------------------------+

和我有销售控制器内部此方法:

And I have inside the Sales controller this method:

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

我如何可以调用查看从主内,使其在每个页面上显示?

How can I call that View from inside the master so that it will be displayed on every page?

推荐答案

您可以使用的 Html.Action或Html.RenderAction 助手。例如,你可以把你的母版页上的以下地方:

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") %>

这将执行控制器动作,渲染视图,并在母版页中指定位置插入生成的HTML。您还可以通过与 [ChildActionOnly] 属性装饰它限制这个动作被只用作子​​操作:

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);
}

这篇关于ASP.NET调用从主网页的控制器的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆