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.)
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.
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.
How do I get my View to stay put, but still pass a message if the ActionResult fails?
Here is the method I'm calling in the controller:
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);
}
Edit: Here's the view:
... dropdown menu called #dd-route...
<a href="#" id="btn-print" class="btn btn-success btn-sm">Generate PDF</a>
<script type="text/javascript">
$(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);
}
})
});
</script>
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.
The second part of the JavaScript is my attempt at displaying the error message if they hit that If statement in the Controller.
TempDataand redirect to the method that generated the original view. In that method, check if the message exists and add it toViewBag<input type='submit'/>and informthis will submit the entire page that might resul in what you describe. If it's GET, how exactly are you loading this page ? default yellow ASP.Net error page is that saying cannot findElectrodeChecklist? If you are performingajax.get()then please share that code..