【问题标题】:Route not getting resolved路线没有得到解决
【发布时间】:2011-01-14 18:54:07
【问题描述】:

我想要干净的 URL 并定义了两条路由:

routes.MapRoute(
    "Search",
    "Search",
    new { controller = "Search", action = "SearchPanel" }
);
routes.MapRoute(
    "SearchResults",
    "Search/{content}",
    new { controller = "Search", action = "Search", content = string.Empty, query = string.Empty, index = 0 }
);

那么我有两个动作:

[HttpPost]
public ActionResult Search(string content, string query)
{
    if (string.IsNullOrEmpty(query))
    {
        return RedirectToAction("Home", "Application");
    }
    return RedirectToAction("Search", new { content = content, query = query }); ;
}

public ActionResult Search(string content, string query, int? index)
{
    if (string.IsNullOrEmpty(query))
    {
        return RedirectToAction("Home", "Application");
    }

    switch (content)
    {
        case "products":
            // get products
            return View("ResultsProducts");
        case "categories":
            // get categories
            return View("ResultsCategories");
        default:
            // get all
            return View("ResultsAll");
    }
}

我的母版页中有一个通用搜索面板,它有一个文本框和一个提交按钮。它发布到/Search。文本框的名称是query。一切都很好。当我点击Search 时,我的第一个操作被执行,但在RedirectToAction() 调用时失败:

路由表中没有路由与提供的值匹配。

我似乎找不到它不起作用的原因。

【问题讨论】:

    标签: asp.net-mvc routing redirecttoaction


    【解决方案1】:

    从第二条路由的默认值中删除contentqueryindex,解决了问题。为什么我真的不能说,因为那些只是定义默认值,当它们没有提供时,在我的情况下并非如此。无论如何,我正在提供这些值。

    【讨论】:

    • 我在更新到 MVC 的第 2 版后遇到了类似的问题。我可以导航到指定 URL 的页面,但是如果我尝试使用 RedirectToAction("ActionName") 我得到了同样的错误:“路由表中没有路由....”在我的情况下,我最终复制了路由条目正在使用 URL 工作并删除了其他参数,现在 RedirectToAction 也可以工作。很奇怪....但是感谢您的提示。
    【解决方案2】:

    我也遇到了同样的问题,谢天谢地,这对我有所帮助,所以我想回馈一些东西。

    似乎 MVC 2 框架发生了变化,迫使您以不同的方式声明路由。

    为了在那里有额外的路由值(例如内容),你不能指定 string.Empty 的默认值,而是有

    content = UrlParameter.Optional
    

    这应该允许您的路线评估表现得像在 MVC 1 中一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 2013-09-30
      • 2019-07-18
      • 2022-01-16
      • 2019-06-28
      • 2013-12-26
      • 2021-05-14
      相关资源
      最近更新 更多