How to check if ViewBag property is null or not exists

C#Jqueryasp.net Mvcasp.net Mvc-3Razor

C# Problem Overview


I have a requirement to execute a script in document.ready function if viewbag property is null or not exists. Below is the code I wrote to check if viewbag property not exists.

I used recommned approached where you @ViewBag.Property!=null but when I do that I get an error saying name property does not exist in current context,

@section scripts {

@if ((bool)ViewData.ContainsKey("FormSubmitFlag") == false)
{
    <script type="text/javascript">
        $(document).ready(function () {

            var pageVisitCount = sessionStorage.getItem("personalDetailsVisitCount");
            if (pageVisitCount == null) {
                $("#personal-details-form").trigger('reset');
                sessionStorage.setItem("personalDetailsVisitCount", "1");
            }
            else {
                var validator = $("#personal-details-form").validate();
                validator.form();
                cat.personaldetails.validate();
            }
        });
    </script>
}
 
}

Thank you

C# Solutions


Solution 1 - C#

You can check for null and execute your script.

@if (ViewBag.YourKey== null)
{
 //your code   
}

This will check that ViewBag.YourKey is null if you want to check it for not null you can change the if condition.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser845405View Question on Stackoverflow
Solution 1 - C#Mairaj AhmadView Answer on Stackoverflow