简体   繁体   中英

How to redirect by common routing

I have the action

public ActionResult Edit(int id)

I need redirect to action Index if id null. How to do this in routing?

I tried:

routes.MapRoute(
                name: "Redirect from empty controller/edit to controller/list",
                url: "{controller}/Edit",
                defaults: new { controller = "Home", action = "Index" }
            );

but it not helped.

Hmm not sure on routing, but if it helps you could use the return RedirectToAction("index", "home"); (Where index is your action method and home is the controller you want to access it on).

Redirection is simple. You can check if id parameter is present by making it nullable. You don't need routing configuration. This will redirect the user to http://example.org/Home when he/she sends a request to http://example.org/Home/Edit

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return RedirectToAction("Index");
    }

    //other logic
}

If you don't want redirection and make Index action respond to a request with http://example.org/Home/Edit URL, you can create a route like this:

routes.MapRoute("HomeEdit", 
                "Home/Edit", new {controller = "Home", action = "Index"});

Just make sure this route is above the default route in RouteConfig.

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