title: Trying to pass error message from Controller to View without page reload (MVC)
body: <p>I'm trying to get my View to display an error message when the ActionResult from my controller fails. (It's triggered when you press a button in the View.)</p>
  
  <p>However, no matter what I try, the ActionResult always redirects to a different page. If I try to return View() it goes to the default yellow ASP.Net error page. If I try to return Content("Error message") it just opens a blank page with that text.</p>
  
  <p>I've saved my canned error message in ViewBag.Error, but the javascript in my View never gets a chance to use it because as soon as you click my button, the ActionResult redirects me somewhere.</p>
  
  <p>How do I get my View to stay put, but still pass a message if the ActionResult fails?</p>
  
  <p>Here is the method I'm calling in the controller:</p>
  
  <pre><code>public ActionResult ElectrodeChecklist(int id)
  {
      var routeChecklist = _routeService.GetRouteChecklist(id);
  
      // This is where I'm trying to catch this error.
      if (routeChecklist.Count == 0)
      {
          ViewBag.Error = "This route has no checklist steps to print.";
          return ???
      }
  
      ...
      blah blah stuff to download a PDF file when everything works
      ...
  
  
      return new BinaryContentResult(buffer, "application/pdf", filename);
  }
  </code></pre>
  
  <p>Edit: Here's the view:</p>
  
  <pre><code>... dropdown menu called #dd-route...
  
  &lt;a href="#" id="btn-print" class="btn btn-success btn-sm"&gt;Generate PDF&lt;/a&gt;
  
  &lt;script type="text/javascript"&gt;
  
      $(function () {
  
          $('#dd-route').change(function () {
              var $route = $(this).val();
              var $url = '@Url.Action("electrodechecklist", "wip")?id=' + $route;
              $('#btn-print').attr('href', $url);
          });
  
          $('#btn-print').click(function () {
              var $error = ViewBag.Error;
              if ($error != "") {
                  $('#alertbar').show();
                  $('#alert').html($error);
              }
          })
  
      });
  
  
  &lt;/script&gt;
  </code></pre>
  
  <p>When the user chooses an item in the dropdown menu, the url to call my ActionResult is fed into the button's href attribute. Then when they click the button, it fires it off with the correct value from the dropdown.</p>
  
  <p>The second part of the JavaScript is my attempt at displaying the error message if they hit that If statement in the Controller.</p>