如何通过与jQuery集成检查TempData是否为null? [英] How can I check if TempData is null through integration with jQuery?

查看:183
本文介绍了如何通过与jQuery集成检查TempData是否为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果TempData不为null,我想显示一个toastr(又名弹出窗口).但是,我在将jQuery和Razor语法集成在一起时遇到了麻烦.这是我当前的javascript:

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

但是,烤面包机没有显示.我已经在进一步检查TempData,以向用户显示文本.

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

我想知道是否有替代方法可以使用上述标记并仅检查此div是否存在,如果存在,请显示烤面包机?或者,也许我可以将两张支票合并为一张?有建议吗?

解决方案

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

$(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.

这篇关于如何通过与jQuery集成检查TempData是否为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆