2010-02-01 65 views
1

我有一个基类控制器类,我想将基类的消息传递给所有控制器,并且该消息可用于所有视图。基础控制器类

我已经创建了一个基本的版本...

部分控制器

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace Website.Controllers 
{ 
    public class SectionController : Controller 
    { 
     // 
     // GET: /Section/ 

     public ActionResult Section() 
     { 
      ViewData["Message"] = "THIS IS A TEST"; 
      return View(); 
     } 

    } 
} 

家庭控制器

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace Website.Controllers 
{ 
    public class HomeController : SectionController 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     } 
    } 
} 

查看

<%= Html.Encode(ViewData["Message"]) %> 

我知道我可以在家庭控制器中做到这一点,但我只是在莫测试。

我没有收到上述任何错误,但我也没有在我的视图中显示消息?

我在使用本教程http://www.asp.net/LEARN/mvc/tutorial-13-cs.aspx好的解决方案部分,如果有帮助。

想我已经得到它的工作现在用下面的代码在我的sectionController ...

namespace Website.Controllers 
{ 
    public class SectionController : Controller 
    { 
     // 
     // GET: /Section/ 

     public SectionController() 
     { 
      ViewData["Message"] = "THIS IS A TEST"; 
      //return View(); 
     } 

    } 
} 

这是一个不错的解决方案吗?

回答

0

您正在将您的ViewData设置为您的基本控制器的Section操作方法,您是否确实希望将其设置在基础控制器的构造函数中?

public SectionController() 
{ 
    ViewData["Message"] = "THIS IS A TEST"; 
} 
+0

这实际上工作,但构造函数是用来建立一个对象。我不认为将一些数据放入ViewData与构建SectionController有任何关系。 – 2010-02-01 15:02:41

+0

我看到我出错的地方我正试图返回一个ActionResult,但我只想让信息可用。我用我目前的解决方案编辑了我的文章。 – Jemes 2010-02-01 15:40:18

+0

我并不是说你的解决方案是错误的或者它不起作用,它肯定会起作用。我只是说构造函数在语义上是填充viewdata的错误地方。 – 2010-02-01 21:48:49

0

HomeController.Index不调用SectionController.Section。

0

因为没有任何请求映射到SectionController中的操作“Section”。如果您映射了域/ Section/Section之类的请求,则会在您的视图中看到您的消息(假设您正在使用默认路由并且具有名为“Section”的视图)。

您需要做的是将您的消息放入viewdata中的每次运行操作时都会运行的方法。你可以做到这一点在OnActionExecuting像:

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    ViewData["Message"] = "THIS IS A TEST"; 
    base.OnActionExecuting(filterContext); 
} 
在SectionController

相关问题