扩展ASP.NET MVC动作方法,如何返回View?

时间:2015-09-11 01:26:31

标签: c# asp.net-mvc

旧:

#

我想扩展“Index()”:

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

如何做返回View()?

1 个答案:

答案 0 :(得分:1)

你想做的事情并不常见。如果你写更多关于你想要的东西,我们可以提供更好的帮助。以下是您尝试做的事情。 System.Web.Mvc.Html.Action调用视图。也就是说,如果下面的代码对某些内容有用,则只能在控制器中使用。在示例中我在SomeController中调用动作"关于"控制器" 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 StackOverflow.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 StackOverflow.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();
    }
}