How do I access ViewBag from JS

前端 未结 5 1799
走了就别回头了
走了就别回头了 2020-12-08 19:51

My attempted methods.

Looking at the JS via browser, the @ViewBag.CC is just blank... (missing)

        var c = \"#\" + \"@ViewBag.CC\";         


        
相关标签:
5条回答
  • 2020-12-08 20:06

    ViewBag is server side code.
    Javascript is client side code.

    You can't really connect them.

    You can do something like this:

    var x = $('#' + '@(ViewBag.CC)').val();
    

    But it will get parsed on the server, so you didn't really connect them.

    0 讨论(0)
  • 2020-12-08 20:17
    <script type="text/javascript">
          $(document).ready(function() {
                    showWarning('@ViewBag.Message');
          });
    
    </script>
    

    You can use ViewBag.PropertyName in javascript like this.

    0 讨论(0)
  • 2020-12-08 20:19

    try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)

    0 讨论(0)
  • 2020-12-08 20:25

    if you are using razor engine template then do the following

    in your view write :

    <script> var myJsVariable = '@ViewBag.MyVariable' </script>
    

    UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

    <head>
     <script>
       var AppConfig = @Html.Raw(Json.Encode(new {
        baseUrl: Url.Content("~"),
        fbApi: "get it from db",
        awsUrl: "get it from db"
       }));
     </script>
    </head>
    

    And you can use it in your JavaScript code as follow:

    <script>
      myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
      alert(myProduct.fullUrl);
    </script>
    
    0 讨论(0)
  • 2020-12-08 20:26

    You can achieve the solution, by doing this:

    JavaScript:

    var myValue = document.getElementById("@(ViewBag.CC)").value;
    

    or if you want to use jQuery, then:

    jQuery

    var myValue = $('#' + '@(ViewBag.CC)').val();
    
    0 讨论(0)
提交回复
热议问题