0

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.

4
  • 1
    Is this a GET method? If so, add the error message to TempData and redirect to the method that generated the original view. In that method, check if the message exists and add it to ViewBag Commented Nov 17, 2016 at 0:11
  • Since we don't' have view part, if it's a button of <input type='submit'/> and in form this 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 find ElectrodeChecklist ? If you are performing ajax.get() then please share that code.. Commented Nov 17, 2016 at 0:21
  • I edited my question to show the View. I didn't use Ajax because Ajax doesn't work very well with downloading things. Commented Nov 17, 2016 at 0:41
  • @StephenMuecke thanks for the TempData suggestion! Used Searching's answer and it works great Commented Nov 17, 2016 at 18:21

2 Answers 2

2

I'm only writing this because it won't fit comments.

OK so first thing to notice is that it WILL start navigating to the Action ElectrodeChecklist with the id and then do what ever BinaryContentResult does. I cannot see how var $error = ViewBag.Error; could possibly work, but then again I'm not sure how/what BinaryContentResult really does.

If you want the user to see the ViewBag.Error then you need to modify this part

if (routeChecklist.Count == 0)
{
    TempData["Error"]  = "This route has no checklist steps to print.";
    return  RedirectToAction("ACTION", "CONTROLLER");
}

as suggested by @StephenMuecke. The ACTION here is the page the user was on in the first place. You could redirect them to any error page and still access the TempData["Error"]. If this still doesn't do what you want let us know.

 //What you are trying to do here is awesome 
 //but I'm not sure if it's even possible as you are moving away from the page when the user clicks the button/link
 //I'd like other please comment on this. I could use it too
$('#btn-print').click(function () {
        var $error = ViewBag.Error;
        if ($error != "") {
            $('#alertbar').show();
            $('#alert').html($error);
        }
    })
Sign up to request clarification or add additional context in comments.

Comments

0

Check below code for without refreshing you can show the error message on page :

 $('#dd-route').change(function () {
  var TestModel = {
  "id": $("route").val()
  }
$.ajax({
                    url: '/wip/electrodechecklist',
                    type: "Post",
                    async: false,
                    data: JSON.stringify(TestModel),
                    dataType: "html",
                    contentType: "application/json;charset=utf-8",
                    success: function (result) {
                        var $error = ViewBag.Error;
            if ($error != "") {
                $('#alertbar').show();
                $('#alert').html($error);
            }
        }
});
});

Hope this will help you !!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.