gpt4 book ai didi

c# - 在 Asp.Net Mvc 中的区域中使用类似的 Controller

转载 作者:行者123 更新时间:2023-11-30 12:47:02 24 4
gpt4 key购买 nike

我正在使用 Asp.Net Mvc 4 开发一个基于体育的网站.

网站正在开发中,一次只显示一项运动数据。

运动有相似的共同数据,但也有不同的数据。

网站支持许多运动,这就是为什么我不想通过使用 if 语句分隔运动来使用通用 Controller / View 。

我试过这个:

我为每项运动创建了一个区域。我在区域中描述了与该运动相关的 Controller 。

例如Route中会写明 Controller 名称和区域,首先在区域中查找,如果没有则默认查找(/Controllers) .

因为 Controller 共享相同的名称,Mvc DefaultControllerfactory 抛出“模糊 Controller 名称异常”。首先,我正在搜索区域,如果找不到,那么我会通过编写自己的 Controller 工厂来默认搜索。您可以借助此 link 访问该项目

在这种情况下,我最大的不足是;没有在路由中指示命名空间在 View 中做同样的事情。所以它会在区域中搜索 View ,如果找不到则默认搜索。因为该项目是主题支持的,所以我使用我自己的可主题化的 razor View 引擎,而不是默认的 razor View 引擎。可以借助此 link 到达

base.AreaViewLocationFormats = new[]
{
_themeService.Current.BasePath + "/Views/Areas/{2}/{1}/{0}.cshtml",
_themeService.Current.BasePath + "/Views/{1}/{0}.cshtml",
_themeService.Current.BasePath + "/Views/Shared/{0}.cshtml","~/Themes/Default/Views/{1}/{0}.cshtml"
};

我像这样更新了 RazorViewEngineAreaViewLocationFormats 对象,但不管我在 route 声明区域的事实如何,它都会搜索 ViewLocationFormats AreaViewLocationFormats 如果我不声明 namespace 。

在这种情况下,我应该如何区分运动?

最佳答案

我在类似情况下所做的是创建一个像这样的基本通用 Controller :

public abstract class BaseController<TModel> : Controller where TModel : class, new()
{
// Controller Actions to be shared by all the controllers that inherit form this one...
}

然后,您的 Controller 将是这样的:

public class TennisController : BaseController<Tennis>
{
}

关于c# - 在 Asp.Net Mvc 中的区域中使用类似的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17968403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com