【问题标题】:How can I shared controller logic in ASP.NET MVC for 2 controllers, where they are overriden如何在 ASP.NET MVC 中为 2 个控制器共享控制器逻辑,它们被覆盖
【发布时间】:2010-05-21 08:00:05
【问题描述】:

我正在尝试实现用户友好的 URL,同时保留现有路由,并且能够使用控制器顶部的 ActionName 标记来实现 (Can you overload controller methods in ASP.NET MVC?)

我有 2 个控制器:

ActionName("UserFriendlyProjectIndex")]
public ActionResult Index(string projectName) { ... }

public ActionResult Index(long id) { ... }

基本上,我要做的是将用户友好的 URL 存储在每个项目的数据库中。

如果用户输入 URL /Project/TopSecretProject/,则会调用操作 UserFriendlyProjectIndex。我进行了数据库查找,如果一切都检查完毕,我想应用在 Index 操作中使用的完全相同的逻辑。

我基本上是在尝试避免编写重复的代码。我知道我可以将通用逻辑分离到另一种方法中,但我想看看在 ASP.NET MVC 中是否有内置的方法。

有什么建议吗?

我尝试了以下方法,然后出现无法找到视图的错误消息:

[ActionName("UserFriendlyProjectIndex")]
public ActionResult Index(string projectName)
{
    var filteredProjectName = projectName.EscapeString().Trim();

    if (string.IsNullOrEmpty(filteredProjectName))
        return RedirectToAction("PageNotFound", "Error");

    using (var db = new PIMPEntities())
    {
        var project = db.Project.Where(p => p.UserFriendlyUrl == filteredProjectName).FirstOrDefault();
        if (project == null)
            return RedirectToAction("PageNotFound", "Error");

        return View(Index(project.ProjectId));
    }
}

这是错误信息:

The view 'UserFriendlyProjectIndex' or its master could not be found. The following locations were searched:
~/Views/Project/UserFriendlyProjectIndex.aspx
~/Views/Project/UserFriendlyProjectIndex.ascx
~/Views/Shared/UserFriendlyProjectIndex.aspx
~/Views/Shared/UserFriendlyProjectIndex.ascx
Project\UserFriendlyProjectIndex.spark
Shared\UserFriendlyProjectIndex.spark

如果有帮助,我将使用 SparkViewEngine 作为视图引擎和 LINQ-to-Entities。 谢谢!

【问题讨论】:

    标签: asp.net-mvc routes


    【解决方案1】:

    作为一个补充,它可能需要优化它以只为项目访问数据库一次......

    ActionName("UserFriendlyProjectIndex")]
    public ActionResult Index(string projectName) 
    { 
        //...
        //var project = ...;
        return IndexView(project);
    }
    
    public ActionResult Index(long id) 
    {
        //...
        //var project = ...;
        return IndexView(project);
    }
    
    private ViewResult IndexView(Project project) 
    {
        //...
        return View("Index", project);
    }
    

    【讨论】:

      【解决方案2】:

      抱歉,我好像在回答我自己的问题!

      我在“包装器”控制器中返回对索引控制器的调用,然后在索引控制器中指定视图名称。

      ActionName("UserFriendlyProjectIndex")]
      public ActionResult Index(string projectName) 
      { 
          //...
          //var project = ...;
          return Index(project.ProjectId);
      }
      
      public ActionResult Index(long id) 
      {
          //...
          return View("Index", project);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-19
        • 2014-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-21
        • 1970-01-01
        相关资源
        最近更新 更多