11

我目前正在尝试从第二个控制器(搜索控制器)重定向到一个控制器(公司控制器)的索引。在我的搜索控制器中,我有以下代码:

RedirectToAction("Index", "Company", new { id = redirectTo.Id, fromSearch = true, fromSearchQuery = q })

但不幸的是,这让我:

/Company/Index/{id}?fromSearch=true&fromSearchQuery={q}

其中 fromSearch 和 fromSearchQuery 是不总是使用的可选参数。

有没有办法直接从 RedirectToAction 获取 URL,以便在我删除字符串的索引部分后将其封装在重定向中,或者使用可选参数设置路由?

4

2 回答 2

11

如果你只想要 URL,你可以使用Url.Actionhelper,它接受所有相同的参数,但只返回 URL。

但是,创建带有可选段和附加段的路线更加困难,因为在中间省略一个段只会导致所有其他段下移,最终您id将取代您的action. 解决方案是在省略可选值时创建与段数和段位置匹配的路线。您还可以使用路由约束来进一步限制路由匹配的内容。

例如,您可以创建此路线:

routes.MapRoute(
    name: "IndexSearch",
    url: "{controller}/{id}",
    defaults: new { action = "Index" },
    constraints: new { action = "Index" }
);

再加上它之后的默认路由:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

将导致助手调用:

RedirectToAction("Index", "Company", new { id = redirectTo.Id, fromSearch = true, fromSearchQuery = q })

创建 URL:/Company/{id}/?fromSearch=true&fromSearchQuery=qactionis Index 或操作被省略时。如果提供了操作并且不是索引,则路由将遵循默认路由。

于 2013-09-08T04:02:15.570 回答
1

您需要正确路由您的请求,因为您将搜索参数作为查询字符串提供。只要有一个搜索路线如下:

routes.MapRoute(
    "CompanySearch",
    "Company/{id}",
    new { controller = "Company", action = "Index" }
);

然后写这个控制器动作

public ActionResult Index(bool fromSearch, string fromSearchQuery)
{
    // do other stuff
}

使用强类型参数(验证方式)

您当然可以创建一个可以验证的类,但属性名称应该反映查询字符串的名称。所以你要么上课:

public class SearchTerms
{
    public bool FromSearch { get; set; }
    public string FromSearchQuery { get; set; }
}

并像现在一样使用具有相同名称的查询变量的相同请求,或者拥有一个干净的类并调整您的请求:

http://domain.com/Company/{id}?FromSearch=true&fromSearchQuery=search+text
于 2013-09-08T03:59:55.857 回答