65

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

Mary
  • 197
  • 1
  • 15
user845405
  • 1,461
  • 5
  • 23
  • 43
  • 1
    Check in html what output this line of code `@if ((bool)ViewData.ContainsKey("FormSubmitFlag") == false)` generates. It would give you better Idea what is going wrong. – Jenish Rabadiya Feb 04 '15 at 04:24
  • using `@ViewBag.Property!=null` should be fine. How were you using it? –  Feb 04 '15 at 04:24
  • possible duplicate of [Checking to see if ViewBag has a property or not, to conditionally inject JavaScript](http://stackoverflow.com/questions/8640927/checking-to-see-if-viewbag-has-a-property-or-not-to-conditionally-inject-javasc) – Mate Feb 04 '15 at 04:25
  • Check this: http://www.codingfusion.com/Post/Check-if-ViewBag-property-is-null-or-not-exists-in-Net-MVC – MaxPayne Aug 11 '23 at 05:22

1 Answers1

131

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.

Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40