0

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.

bnil
  • 1,531
  • 6
  • 35
  • 68
  • You are not closing the div tags in append method! – stackunderflow May 13 '14 at 08:12
  • its kind of pseudo code... its working in my code... I get the error regarding the data. see in my comment... – bnil May 13 '14 at 08:55
  • A quick google search of "razor syntax javascript" shows two stackoverflow [questions](http://stackoverflow.com/questions/4599169/using-razor-within-javascript) that should [help you](http://stackoverflow.com/questions/4045308/razor-syntax-and-javascript). The words might be different but the problem is the same. –  May 13 '14 at 08:58
  • Then r u sure the viewBags isn't empty!! Don't you receive compile time error? – stackunderflow May 13 '14 at 10:25

2 Answers2

0

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.

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
  • Tried , Error comes as VileParle is not defined Error is - > function AddDivs() { var ht= ""; ht += "
    "; ht += "
    "; ht += "
    "; ht += "
    "; ht += "
    "; ht += "
    "; return ht; }
    – bnil May 13 '14 at 08:42
  • cant assign the values to ht, is important ? – bnil May 13 '14 at 09:05
0

script tag must be inside of body tag

        <script type="text/javascript">
             ...                
        </script>
     </body>
</html>
binard
  • 1,726
  • 1
  • 17
  • 27