扩展 ASP.NET MVC 操作方法。 return如何查看?

Extend ASP.NET MVC action method. How to do return View?

旧:

public class HomeController : Controller {
    public ActionResult Index()
    { 
        // do something 
          return View();
    }
}  

我想延长Index():

public static class HomeControllerExtensions{
   public static ActionResult Index(this HomeController hc,string viewName)
   { 
    // do something 
    return View(viewName);//hc.View cannot...., how to do return View()?
}}   

如何returnView()?

为了作为一个动作暴露给宇宙,一个方法必须满足特定的要求:

  • 方法必须是public。
  • 该方法不能是静态方法。
  • 该方法不能是扩展方法。
  • 该方法不能是构造函数,getter,或setter。
  • 该方法不能有开放泛型类型。
  • 该方法不是控制器库的方法class。
  • 该方法不能包含 ref 或 out 参数。

因此该方法不能用作动作。

但是如果它是一个不会是动作的扩展方法,您可以使用您的 hc 参数来访问 Controller 的方法,例如 View()View(string) , ...

作为替代方案,您可以考虑向您的项目添加一个基本控制器 class,您的所有控制器都可以从它继承,并且在您的基本控制器 class 中,您可以添加自定义操作方法,重写controller的一些方法等等

你想做的事情不常见。如果你写更多关于你想要的东西,我们可以提供更好的帮助。以下是您要执行的操作。 System.Web.Mvc.Html.Action 调用了一个视图。也就是说,如果下面的代码对某些东西有用,则只能在控制器中使用。在示例中,我在 SomeController 中调用操作 "About" 控制器 "Home" 使用您要创建的扩展。

扩展代码:

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

namespace Whosebug.Controllers
{
    public static class ControllersExtensions
    {
        public static ActionResult Index(this HomeController controller, string ViewName)
        {
            string controllerName = controller.GetType().Name.Replace("Controller", "");
            RouteValueDictionary route = new RouteValueDictionary(new
            {
                action = ViewName,
                controller = controllerName
            });

            RedirectToRouteResult ret = new RedirectToRouteResult(route);

            return ret;
        }
    }
}

SomeController:

namespace Whosebug.Controllers
{
    public class SomeController : Controller
    {
        //
        // GET: /Some/

        public ActionResult Index()
        {
            HomeController home = new HomeController();

            return home.Index("About");
        }

    }
}

家庭控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}