简体   繁体   中英

How to display viewbag elements in Javascript?

How to call the Method in Jquery's Append Method ?

I have the HTML code in which I use the append method() on click of a button. I want to append the HTML with viewbag data using loop. here is my code , is that right ?

        <html>
        <body>
        <div class="row-fluid" id="MyCode">
        </div>
        <button name="AddCode"></button>
        </body>
        </html>

         <script type="text/javascript">

         $(document).ready(function ()
           {

               $('#AddCode').click(function () {

                     $('#MyCode').append("<di ><div class='span2'>" +

                      //I want to call the function here... 
                     AddDivs()
           );

        });

 function AddDivs()
 {
  var ht="";
  @foreach (var item in ViewBag.LocationList)
{
 ht += "<div id='"+item.Id+"_"+item.Name+"'></div>";
  }
  }

 });
 </script>

Its showing undefined.

Change foreach loop with following:

@foreach (var item in ViewBag.LocationList)
{
    // these lines are client codes that is in server codes
    <text>ht += "<div id='" + @item.Id + "_" + @item.Name + "'></div>";</text>
}

if you dont write your js codes in <text> , razor assume that ht is an server variable.

script tag must be inside of body tag

        <script type="text/javascript">
             ...                
        </script>
     </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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