Bob Tway
Bob Tway

Reputation: 9613

ASP.NET MVC - how to pass parameters to actions on a different controller

Working on an MVC site that was constructed by another developer, who has now left. I'm not that hot on MVC, so apologies if this is a terrible question.

Among the controllers for this site there is an ErrorController. It has two associated Views held in \Views\Error. The controller doesn't do much:

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View("NotFound");
    }

    public ActionResult Error()
    {
        return View("Error");
    }
}

I'm trying to extend this controller so I can pass in an error message and inform the user, but I'm struggling to understand how I can pass a parameter to it when I'm calling from a different controller. So, for example this:

public class ManagerController : Controller
{
    public ActionResult SubmitDetails()
    {
        if (ModelState.IsValid)
        { 
            // do stuff and return a View
        }

        //if we get this far, we've got an error or an invalid state
        return View("../Error/Error");
    }
}

Render the error view. But if add this to the ErrorController:

    public ActionResult Error(string errorMessage)
    {
        ViewBag.ErrorMessage = errorMessage;
        return View("Error");
    }

I don't know how I can call that from an action in a different controller. Variants on the theme of:

return View("../Error/Error", "test error message");

Results in an error: The view '../Error/Error' or its master was not found or no view engine supports the searched locations.

How can I pass a message, or better yet an object with a bunch of messages, down to the controller? Or am I going about this the wrong way - the full error messages suggests I should perhaps be using a shared view instead?

Upvotes: 0

Views: 736

Answers (2)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

You need to use RedirectToAction("ActionName","ControllerName")

In your case its

return RedirectToAction("Error", "Error");

To pass values between controllers you must use TempData[]

Also you can pass data as parameters like below.

return RedirectToAction("Error", "Error", new { errorMessage = "Your Error Message Here" });`

Upvotes: 2

Giorgi Merebashvili
Giorgi Merebashvili

Reputation: 43

Just use Redirect instead of return View... like this

return RedirectToAction("Error", "ErrorMesige");

Upvotes: 3

Related Questions