Dmytro
Dmytro

Reputation: 17176

What is the best approach to share data between controllers in ASP .NET MVC?

I have two controllers:

public class AController : Controller
{
      public ActionResult AControllerAction()
      {
          if (// BControllerAction reported an error somehow )
          {
                ModelState.AddModelError("error-key", "error-value");
          }
          ...
      }
}

public class BController : Controller
{
      public ActionResult BControllerAction()
      {
          try{Something();}
          catch(SomethingExceprion)
          {
              // here I need to add error info data,
              // pass it to AController and redirect to
              // AControllerAction where this error will be added 
              // to model state
          }
      }
}

I think I can do something like:

public ActionResult BControllerAction()
{
     try{Something();}
     catch(SomethingException)
     {
         var controller = new AController();
         controller.ModelState.AddModelError("error-key", "error-value");
         controller.AControllerAction();
     }
}

But I suggest it will be architecture breaking approach, and I don't want to do like that. Is there some simpler and safer way, except passing model object?

Upvotes: 3

Views: 6994

Answers (2)

yoozer8
yoozer8

Reputation: 7489

You can return a redirect to AControllerAction. You can use the TempData dictionary (similar to ViewData) to share data across such a call (data stored this way will persist to the next request in the same session, as explained in this blog post).

Example:

public class AController : Controller
{
      public ActionResult AControllerAction()
      {
          if (TempData["BError"] != null)
          {
                ModelState.AddModelError("error-key", "error-value");
          }
          ...
      }
}

public class BController : Controller
{
      public ActionResult BControllerAction()
      {
          try{Something();}
          catch(SomethingExceprion)
          {
              TempData["BError"] = true;
              return RedircetToAction("AControllerAction", "AController");
          }
      }
}

Upvotes: 2

Forty-Two
Forty-Two

Reputation: 7605

Depending on what details of the exception you need to pass back to Controller A, I would do something along the lines of

public ActionResult BControllerAction()
{
     try{Something();}
     catch(SomethingException ex)
     {
         return RedirectToAction("AControllerAction", "AController", new { errorMessage = ex.Message() })
     }
}

And then change the signature of the called method to

public ActionResult AControllerAction(string errorMessage)
      {
          if (!String.IsNullOrEmpty(errorMessage))
          {
                //do something with the message
          }
          ...
      }

Upvotes: 3

Related Questions