Search code examples
javascriptasp.net-mvc-3asp.net-mvc-ajax

To load an Iframe dynamically on click of a link in MVC3


Hi i am developing an application inMVc3
I have a model containing

Hobbyname 
Hobbyurl

I have drawn a table and in the first column i fetch all the hobbynames and display it as a link. Hobbyurl contains the url of a page associated with the Hobbyname Now when i click the Hobbyname from lefthand side i want the contents to be loaded in the right side i use an Iframe to display the contents so i need the Iframe to be loaded again and again on click.

To fetch the Hobbynames i used the foll code:

 <td>
 <ul>
  @foreach (var item in Model)
  {
   <li> @Html.ActionLink(item.HobbyName, "Hobbies")</li>
  }
 </ul>
 </td>
 <td>
 <div>
 <iframe id="iframe"></iframe>
 </div>
 </td>

and Here is the script:

<script type="text/javascript">
$('a').click(function () {
    $('iframe').attr('src', "/HobbyHomes/Test");
}); 
</script>

But i am not able to load the Iframe on click of the link. Please help me


Solution

  • your probably wanting to attach your onclick after the dom is loaded, like so

    <script type="text/javascript">
    $(document).ready(function(){
      $('a').click(function (e) {
        e.preventDefault();
        $('iframe').attr('src', "/HobbyHomes/Test");
      }); 
    });
    </script>