且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过与jQuery集成检查TempData是否为null?

更新时间:2022-10-23 08:18:59

我能够通过以下代码使用它:

$(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!");
    }
});

对于任何好奇的人,我都必须呼叫ToLower(),因为TempData总是返回TrueFalse,而不是truefalse. 此处进行了解释.. >

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?

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.