开发者

Base controller class

开发者 https://www.devze.com 2022-12-18 12:41 出处:网络
I have a base controller class and I would like to pass a Message from the Base class to all controllers and for that message to be available to all views.

I have a base controller class and I would like to pass a Message from the Base class to all controllers and for that message to be available to all views.

I've created a basic version below...

Section 开发者_如何学CController

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

    }
}

Home Controller

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

View

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

I know I can do this in the home controller but I'm just testing at the mo.

I'm not getting any errors with the above but I'm also not displaying the message on my view?

I'm using this tutorial http://www.asp.net/LEARN/mvc/tutorial-13-cs.aspx The Good Solution part, if that helps.

Think I've got it working now used the code below on my sectionController...

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

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

    }
}

Is this an ok solution?


You're setting your ViewData in the Section action method of your base controller, do you actually want to be setting it in the constructor of your base controller?

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


HomeController.Index isn't calling SectionController.Section.


Because none of the requests are mapped to action "Section" in SectionController. If you mapped a request like domain/Section/Section, you would see your message in your view (Assuming that you are using default routing and have a view named "Section").

What you need to do is, placing your message into the viewdata on a method that runs every time an action is run. You can do it in OnActionExecuting like:

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

in the SectionController.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号