简体   繁体   中英

Re-direct loop when checking if value is null C#

I am getting results based on an ID which is passed into the controller via the URL, for example Site/View/12 - this will bring back all results that match 12.

However, if there are no results, I want to re-direct back to the Index page which also has the search field.

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);
    }
}

However, whilst trying to view any page (/Add, /Index etc) I get a "This webpage has a redirect loop" error.

I'm not quite sure what's going on, because as far as I can tell viewing these pages shouldn't even trigger anything inside ActionResult View() . Also, the RedirectToAction is going to Index - so I cannot figure out where the loop is.

If I remove the line return RedirectToAction("Index", "Home"); the application functions normally.

Any advice would be very welcome, thank you.

(edit) Here's the Index controller:

public ActionResult Index()
{
    return View();
}

And here's the RouteConfig.cs file:

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 }
    );
}

The controller has a View method to return the view, but your Action method is also named View, and that's where it gets stuck. Change your action to be:

[ActionName("View")]
public new ActionResult ViewItem(string ID = "")

And everything should work OK.

Your action is named View . When you do

public ActionResult Index()
{
    return View();
}

it's defaulting to your method (the optional parameter makes it valid):

public new ActionResult View(string ID = "")

If you mouseover return View() intellisense will tell you which View() its calling. Rename your View action and you'll see that the intellisense changes which View() is referenced, and it should work fine. Using an attribute to keep your action as View seems like its just going to cause another confusing headache later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM