[英]Re-direct loop when checking if value is null C#
我正在基于通过URL传递到控制器的ID获得结果,例如Site / View / 12-这将带回所有匹配12的结果。
但是,如果没有结果,我想重定向回具有搜索字段的“索引”页面。
public new ActionResult View(string ID = "")
{
XDocument xml = XDocument.Load(xmlPath);
var bikes = (xml).ToList();
if (!bikes.Any())
{
return RedirectToAction("Index", "Home");
}
else
{
return View(bikes);
}
}
但是,在尝试查看任何页面(/ Add,/ Index等)时,出现“此网页具有重定向循环”错误。
我不太确定发生了什么,因为据我所知,查看这些页面甚至不应该在ActionResult View()
内部触发任何事件。 另外, RedirectToAction
将要建立Index
-因此我无法弄清楚循环在哪里。
如果我删除该行,则return RedirectToAction("Index", "Home");
该应用程序正常运行。
任何建议都将非常欢迎,谢谢。
(编辑)这是Index控制器:
public ActionResult Index()
{
return View();
}
这是RouteConfig.cs文件:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
控制器有一个View方法来返回视图,但是您的Action方法也被称为View,这就是它被卡住的地方。 将您的操作更改为:
[ActionName("View")]
public new ActionResult ViewItem(string ID = "")
一切都应该正常。
您的操作名为View
。 当你做
public ActionResult Index()
{
return View();
}
它默认为您的方法(可选参数使其有效):
public new ActionResult View(string ID = "")
如果将鼠标悬停在return View()
Intellisense会告诉您调用哪个View()
。 重命名您的View
操作,您将看到intellisense更改了所引用的View()
,它应该可以正常工作。 使用属性将您的操作保留为View
似乎会在稍后引起另一个令人困惑的头痛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.