【问题标题】:Whats wrong with my routes and actions?我的路线和行动有什么问题?
【发布时间】:2013-04-19 15:33:48
【问题描述】:

我最近问了一个关于如何根据包含以下内容的内容表创建页面的问题:TitleContent。据我所知,我按照answer that was given 中的步骤进行操作。

我创建了这样的路线:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "ContentManagement",
            "{title}",
            new { controller = "ContentManagement", action = "Index", title = "{title}" }
        );

    }

我假设我可以做这样的路线?在哪里可以设置多条路线?我还假设我可以像我所做的那样将标题传递给控制器​​操作?

然后我创建了模型:

namespace LocApp.Models
{
    public class ContentManagement
    {
        public int id { get; set; }
        [Required]
        public string title { get; set; }
        public string content { get; set; }
    }
}

由此我创建了一个控制器,其索引操作如下所示:

    public ViewResult Index(string title)
    {
        using (var db = new LocAppContext())
        {
            var content = (from c in db.Contents
                           where c.title == title
                           select c).ToList();

            return View(content);

        }
    }

然后我创建了一些 title 为“bla”的内容,所以当我访问 site.com/bla 时,我收到一个错误,它找不到“bla/”

谁能告诉我我做错了什么?如果您熟悉带有顶部选项卡的 asp.net mvc 项目的默认布局,我也会根据数据库中的标题创建一组指向页面的选项卡

【问题讨论】:

标签: asp.net-mvc-3 entity-framework razor entity


【解决方案1】:

主要问题是,当您使用标题时,路由引擎会将其与第一个路由匹配,并尝试通过该标题查找控制器。我们已经实现了类似的东西,并发现通过明确定义哪些控制器对默认路由有效,然后它会适当地处理请求。我在下面给出了一个我们允许适合我们默认路由的控制器示例(Home、Help 和 Error)。

您可能还希望阻止人们为内容提供与您的根级别控制器相同的 TITLE,因为这会导致问题非常严重。

    public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new {controller = "Home", action = "Index", id = UrlParameter.Optional},
                new {controller = "Home|Error|Help"},
                new[] {"UI_WWW.Controllers"});

            routes.MapRoute(
                "ContentManagement",
                "{title}",
                new {controller = "ContentManagement", action = "Index"});    

            }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 2011-04-15
    • 1970-01-01
    • 2018-03-06
    • 2013-11-18
    相关资源
    最近更新 更多