简体   繁体   English

检入javascript代码是否存在来自会话的对象

[英]Check in javascript code if object from session is exist

In View.cshtml I have a section where I check if in session exists object named Reservation 在View.cshtml中,我有一个部分可以检查会话中是否存在名为Reservation的对象。

<head>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")

    <script type="text/javascript">
        $(function () {
            if ( @Session["Reservation"] ) 
            {
                $('.reservationDetails :input').attr("disabled", false));
                $('#termSection :input').attr("disabled", true);
            }
        });
    </script>

</head>

When the first time page is loaded button with id termSection is active, but when in other action I save object Reservation in session this button still is active then I redirects to View.cshtml. 当第一次加载页面时,具有id termSection的按钮处于活动状态,但是在其他操作中,我将对象保留保存在会话中时,该按钮仍然处于活动状态,然后重定向到View.cshtml。 I think the problem lies in this condition to check if Object from sesssion is null. 我认为问题出在这种情况下,以检查来自sesssion的对象是否为空。

I suggest you move the if condition to the server side. 我建议您将if条件移到服务器端。 If the reservation isn't present, just don't render the Javascript at all. 如果不存在保留,则根本不呈现Javascript。

So, instead of 所以,代替

if ( @Session["Reservation"] ) 

Use 采用

@if ( Session["Reservation"] != null )

In context: 在上下文中:

@if ( Session["Reservation"] != null )
{
     $('.reservationDetails :input').attr("disabled", false));
     $('#termSection :input').attr("disabled", true);
}

If Reservation is not null, the output Javascript will be: 如果Reservation不为null,则输出Javascript将为:

$(function () {
    $('.reservationDetails :input').attr("disabled", false));
    $('#termSection :input').attr("disabled", true);
}

If Reservation is null, the output Javascript will be: 如果Reservation为null,则输出Javascript将为:

$(function () {
}

In other words, it won't do anything, which seems to be the intention. 换句话说,它什么也不会做,这似乎是意图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM