如何重定向到索引操作,但从网址中删除“索引/”?

时间:2013-09-08 03:01:31

标签: asp.net asp.net-mvc asp.net-mvc-4

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

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

但不幸的是,这需要我:

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

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

有没有办法直接从RedirectToAction获取URL,所以我可以在删除字符串的Index部分后将其包含在Redirect中,或者使用可选参数设置路由?

2 个答案:

答案 0 :(得分:9)

如果您只想要URL,可以使用Url.Action帮助器,它使用所有相同的参数,但只返回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 })

action为索引或省略操作时,创建URL: / Company / {id} /?fromSearch = true& fromSearchQuery = q 。如果提供了操作,并且不是“索引”,则路由将推迟到默认路由。

答案 1 :(得分:0)

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

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
相关问题