Phi*_*esi 7 asp.net asp.net-mvc asp.net-mvc-4
我目前正在尝试从第二个控制器(搜索控制器)重定向到一个控制器(公司控制器)的索引.在我的搜索控制器中,我有以下代码:
RedirectToAction("Index", "Company", new { id = redirectTo.Id, fromSearch = true, fromSearchQuery = q })
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这需要我:
/Company/Index/{id}?fromSearch=true&fromSearchQuery={q}
Run Code Online (Sandbox Code Playgroud)
其中fromSearch和fromSearchQuery是不常用的可选参数.
Is there a way to either directly get the URL from RedirectToAction so I can encase it in a Redirect after I chop out the Index part of the string, or set up routes with the optional parameters?
如果您只想要URL,您可以使用Url.Action
获取所有相同参数的助手,但只返回URL.
但是,创建带有可选线段后跟其他线段的路线更加困难,因为在中间省略一个线段只会导致所有其他线段向下移动,您将id
最终取代您的线路action
.解决方案是在省略可选值时创建与段数和段的位置匹配的路径.您还可以使用路径约束来进一步限制路径匹配的内容.
例如,您可以创建此路线:
routes.MapRoute(
name: "IndexSearch",
url: "{controller}/{id}",
defaults: new { action = "Index" },
constraints: new { action = "Index" }
);
Run Code Online (Sandbox Code Playgroud)
加上后面的默认路线:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
会导致帮助者调用:
RedirectToAction("Index", "Company", new { id = redirectTo.Id, fromSearch = true, fromSearchQuery = q })
Run Code Online (Sandbox Code Playgroud)
当索引或操作被省略时,创建URL:/ Company/{id} /?fromSearch = true&fromSearchQuery = qaction
.如果提供了操作并且不是"索引",则路由将遵循默认路由.