扩展ASP.NET MVC的操作方法,怎么办返回查看? [英] extend ASP.NET MVC action method,How to do return View?

查看:99
本文介绍了扩展ASP.NET MVC的操作方法,怎么办返回查看?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

老:

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

我想延长索引()

I want extend "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()?
}}   

怎么办返回查看()?

how to do return View()?

推荐答案

您想要做的是不常见的。如果你写更多关于你想要什么,我们可以帮助更好。下面是你想要做什么。视图是由System.Web.Mvc.Html.Action调用。也就是说,如果在$ C $下面c是为一些有益的,只能在控制器中使用。在这个例子中我在SomeController调用动作关于控制器家用你要创建的扩展。

What you want to do is not common. If you write more about what you want exactly, we can help better. Below is what you're trying to do. A view is invoked by System.Web.Mvc.Html.Action. That is, if the code below is useful for something, can only be used in a controller. In the example I'm in the SomeController calling the action "About" the controller "Home" using the extension you want to create.

该扩展code:

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:

The SomeController:

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

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

            return home.Index("About");
        }

    }
}

Home控制器:

The Home Controller:

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

这篇关于扩展ASP.NET MVC的操作方法,怎么办返回查看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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