目标: 我希望能够输入 URL:www.mysite.com/NewYork 或 www.mysite.com/name-of-business
根据字符串,我想在不更改 URL 的情况下路由到不同的操作。
到目前为止我有:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"UrlRouter", // Route name
"{query}", // URL with parameters
new { controller = "Routing", action = "TestRouting" } // Parameter defaults
);
}
在我的 Controller 中:
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
return RedirectToAction("Index", "Availability"); // <--------- not sure
else if (query == "name-of-business")
return Redirect("nameofbusines.aspx?id=2731"); // <--------- not sure
else
return RedirectToAction("TestTabs", "Test"); // <--------- not sure
}
我已经尝试了很多方法来重定向/转移到页面而不需要 更改 URL,但我尝试过的所有操作都更改了 URL 或给我一个错误。
基本上我正在寻找 server.transfer 的等价物,我可以在其中保留 URL 但将信息发送到操作并让它显示其结果。
最佳答案
在这方面我支持 Nick,但我认为您可以只使用常规 View 而不必进行局部 View 。如果它们不在对应于 Controller 的 View 中,您可能需要将它们实现为共享 View (因为它只会查看关联和共享的 View )。
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
{
var model = ...somehow get "New York" model
return View("Index", model );
}
else if (query == "name-of-business")
{
var model = ...get "nameofbusiness" model
return View("Details", model );
}
else
{
return View("TestTabs");
}
}
然后每个 View 将采用模型的特定实例并使用模型呈现它的内容。 URL 不会改变。
任何时候您使用 RedirectResult,您实际上都会向浏览器发送 HTTP 重定向,这将强制更改 URL。
关于c# - ASP MVC 重定向而不改变 URL(路由),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/752922/