返回不同区域的视图

发布于 2024-09-15 23:20:32 字数 231 浏览 2 评论 0原文

我的 ASP.NET MVC 2 应用程序分为几个区域。其中一个是主目录中的默认区域,另一个是区域目录中的Account 区域。现在的问题是我需要在这两个区域的控制器中使用相同的视图。

如果它们位于同一区域,我只需返回 View("ViewName"),但是我该怎么做才能从我的Account控制器中的默认区域返回视图呢?代码>区域?有什么想法吗?

I have my ASP.NET MVC 2 application divided into few areas. One of them is a default area in the main catalog, and the other is an Account area in the Areas catalog. Now, the problem is that I need to use the same view in controllers from both of these areas.

If they were in the same area, I would just return View("ViewName"), but what can I do to return a view from my default area in a controller from my Account area? Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆里有你的影子 2024-09-22 23:20:33

这是一个老问题,但我认为在 MVC 中仍然是一个相关问题,所以这里是我如何以 DRY 方式解决它,让您轻松更改服务器路径,并自动更新所有依赖操作:

public class FooController : Controller
{

    private ActionResult FooView(string name, string extension = "cshtml") { 
        return View("~/Areas/Bar/Views/Foo/" + name + "." + extension); }
    }


    public ActionResult SomeAction(){

      return FooView("AreaSpecificViewName");

    }

    public ActionResult SomeOtherAction(){

      return FooView("AnotherAreaSpecificViewName", "aspx");

    }

}

这很简洁,因为它是默认的到 Razor (.cshtml) 视图文件,但可以通过提供第二个参数来显式设置,如 SomeOtherAction() 中所示。

它简单但方便,特别是在开发过程中,当您的区域路径可能发生变化或发生其他情况时。

希望对某人有帮助。

This is an old question but still a relevant issue in MVC I think, so here is how I solve it in a DRY fashion that lets you easily change the server path, and have all your dependent actions update automatically:

public class FooController : Controller
{

    private ActionResult FooView(string name, string extension = "cshtml") { 
        return View("~/Areas/Bar/Views/Foo/" + name + "." + extension); }
    }


    public ActionResult SomeAction(){

      return FooView("AreaSpecificViewName");

    }

    public ActionResult SomeOtherAction(){

      return FooView("AnotherAreaSpecificViewName", "aspx");

    }

}

This is neat because it defaults to Razor (.cshtml) View files, but it can be set explicitly by supplying the second parameter, as seen in SomeOtherAction().

It's simple but handy, especially during development when the path of your Area might change or something.

Hope that helps someone.

此生挚爱伱 2024-09-22 23:20:32

您可以指定视图的相对位置:

return View("~/Views/YourArea/YourController/YourView.aspx");

但是当视图在多个区域之间共享时,我建议您使用 ~/Views/Shared 文件夹,它可以更好地实现此目的。

You could specify the relative location of the view:

return View("~/Views/YourArea/YourController/YourView.aspx");

But when a view is shared among multiple areas I would recommend you to use the ~/Views/Shared folder which serves better this purpose.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文