-2

Here I have ViewBag in a controller which contains text i.e ViewBag.Msg = "No Sprint".
And I am trying to use ViewBag.Msg in Jquery to display modal.
Now, the problem is that the script is script never gets executed.

Below is my jQuery.

 <script>
    $(document).ready(function () {
        debugger;
        if (@ViewBag.Msg != null)
        {
            $("#myModal").modal();
        }
    });
</script>


Any help will be highly appreciated. Thank You.

Mamun
  • 66,969
  • 9
  • 47
  • 59
CarrotCrop
  • 73
  • 1
  • 5
  • 12
  • What is the resulting client-side code? Did you just forget to enclose a string in quotes? Check your browser console for errors. – David Oct 14 '17 at 11:22
  • Possible duplicate of [How do I access ViewBag from JS](https://stackoverflow.com/questions/10008023/how-do-i-access-viewbag-from-js) – adiga Oct 14 '17 at 11:38

2 Answers2

1

You need to use quotation marks for the view bag, as it will appear as a literal string.

If your debugger is not hitting at all, then you have another issue, post your full code. (your .cshtml file and layout)

 <script>
    $(document).ready(function () {
        debugger;
        if ('@ViewBag.Msg' != null)
        {
            $("#myModal").modal();
        }
    });
 </script>
Ziv Weissman
  • 4,400
  • 3
  • 28
  • 61
0

Please use the below code.

<script>
    $(document).ready(function () {
        debugger;
        var msg='@ViewBag.Msg';
        if (msg !== '')
        {
            $("#myModal").modal();
        }
    });
</script>
Aman Bachas
  • 264
  • 1
  • 6