jwaliszko
jwaliszko

Reputation: 17064

MVC3 Url.Action() not working as expected after invoking controller action using Execute

I'm on some page in my MVC3 application. The URL in the browser is http://localhost:60901/MyApp/Ideas/Create/. Now I get an exception on this page after posting some data. I have error handling. Simplified version is shown below.

Global.asax

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    RouteData routeData = new RouteData();
    routeData.Values.Add("action", "General");            
    routeData.Values.Add("e", exception);

    using (ErrorController errorController = new ErrorController())
    {
        ((IController)errorController).Execute(new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData));
    }
}

ErrorController.cs

public class ErrorController : Controller
{        
    public ActionResult General(Exception e)
    {
        ViewBag["ReturnToUrl"] = Url.Action("Index", "Ideas");
        return View();
    }
}

The ReturnToUrl in ViewBag suprisingly is //Ideas/Index/ What with the MyApp prefix ? Normally, Url.Action("Index", "Ideas") returns /MyApp/Ideas/Index/. Is there something wrong with the controller context ? How to fix this ?

Upvotes: 0

Views: 3834

Answers (3)

jwaliszko
jwaliszko

Reputation: 17064

I've found the problem. It was my mistake. I missed the case, that all routes in the system I'm currently working with, are defined as below:

routes.MapRoute(
     "Default", // Route name
     "{application}/{controller}/{action}/{*id}", // URL with parameters
     new { controller = "Welcome", action = "Index", id = UrlParameter.Optional, application = UrlParameter.Optional } // Parameter defaults
            );

They have an {application} parameter at the beginning (before the {controller} parameter).

Previously, I didn't pass this parameter to the ErrorController. After passing it

routeData.Values.Add("application", "MyApp");

program works as expected.

Upvotes: 0

covo
covo

Reputation: 540

Jarek,

Is "MyApp" an Area of your application? If so, you can specify the area as part of the route values as so:

Url.Action("Action", "Controller", new { Area = "MyApp" });

If "MyApp" is not an area, maybe you can explain your configuration a bit more.

Hopet this helps,

-covo

Upvotes: 1

John
John

Reputation: 3546

Why not just set the ViewBag["ReturnToUrl"] = "/MyApp/Ideas/Index/" manually.

Upvotes: 1

Related Questions