How can I check if TempData is null through integration with jQuery?

The Vanilla Thrilla picture The Vanilla Thrilla · May 5, 2015 · Viewed 24.9k times · Source

I would like to show a toastr (aka a popup) if TempData isn't null. However, I'm having trouble integrating the jQuery and Razor syntax together. This is my current javascript:

$(document).ready(function() {
        if (@TempData["SuccessMessage"] != null) {
            toastr.options = {
                "closeButton": true,
                "positionClass": "toast-bottom-right"
            }
            toastr.success("This is a test!");
        }
});

However, the toastr isn't displaying. I'm already checking TempData further up to also display text to the user.

@if (TempData["SuccessMessage"] != null)
{
    <div class="success-message">
        @Html.Raw(@TempData["SuccessMessage"].ToString())
    </div>
}

I'm wondering if an alternative would be to somehow use the above markup and just check if this div exists, and if so, show the toastr? Or perhaps I can integrate the two checks into one? Suggestions?

Answer

The Vanilla Thrilla picture The Vanilla Thrilla · May 12, 2015

I was able to get it working with the following code:

$(document).ready(function() {
    var success = @((TempData["SuccessMessage"] != null).ToString().ToLower());

    if (success == true) {
        toastr.options = {
            "closeButton": true,
            "positionClass": "toast-bottom-right"
        }
        toastr.success("Success!  You're now registered for Lose A Ton!");
    }
});

For anyone curious, I had to call ToLower() because TempData would always return True or False, rather than true or false. The reasons for this are explained here.