title: Is it good practice to pass TempData and/or ViewData to services?
body: <p>In trying to reduce the size of my MVC controllers, I am refactoring a lot of logic out into services (though this same issue would apply if it was being factored into models).  I'm often finding that I was directly setting <code>ViewData</code> and/or <code>TempData</code> with information I wanted to be displayed to the user, like:</p>
  
  <pre><code>var repoUser = new UserRepository();
  var foundUser = repoUser.GetUser(userId);
  if (foundUser == null) {
      ViewData["ErrorMessage"] = "Could not find user with ID {0}.".FormatWith(userId);
      return View("UsersRegister");
  }
  </code></pre>
  
  <p>Of course, as soon as you move into a service class, you lose direct access to <code>ViewData</code>, <code>TempData</code>, and methods like <code>View()</code> or <code>RedirectToAction()</code>, so I'm trying to figure out the best practice for dealing with it.  Two solutions come to mind:</p>
  
  <ol>
  <li><p>Create a class containing various pieces of information about what the controller should do, to be passed back from the services, like:</p>
  
  <pre><code>public class ResponseInfo {
      public string Name { get; set; }
      public bool DoRedirect { get; set; }
      public object RedirectRouteValues { get; set; }
      public string InfoMessage { get; set; }
      public string ErrorMessage { get; set; }
  }
  </code></pre></li>
  <li><p>Try and allow the service methods to have direct access to things like <code>ViewData</code> and <code>TempData</code>, eg.:</p>
  
  <pre><code>public ActionResult ToggleUserAttended(int eventId, int userId, HttpRequestBase request, TempDataDictionary tempData, ViewDataDictionary viewData, Func&lt;string, object, ActionResult&gt; redirectAction) {
      //...
      var repoUser = new UserRepository();
      var foundUser = repoUser.GetUser(userId);
      if (foundUser == null) {
          tempData["ErrorMessage"] = "Could not find user with ID {0}.".FormatWith(userId);
          return redirectAction("UsersRegister", new { id = eventId, returnUrl = request.QueryString["returnUrl"] });
      }
      //...
  }
  </code></pre>
  
  <p>... and then in the controller:</p>
  
  <pre><code>return _svcEvent.ToggleUserAttended(123, 234, Request, TempData, ViewData, (name, routeVals) =&gt; RedirectToAction(name, routeVals));
  </code></pre></li>
  </ol>
  
  <p>For number 1, the controller would have more logic to do in looking at the <code>ResponseInfo</code> object and determining whether to redirect, display a view, plugging the error or info message into <code>TempData</code> or <code>ViewData</code>, etc.  Number 2 would pretty much allow a one-liner controller, but you're making the service very aware of controller-specific stuff.  However, the service is always going to be closely tied in with the controller anyway so is this a problem?  Would 1 or 2 be best practice, or something else I haven't listed?</p>