Java Nerd
Java Nerd

Reputation: 968

Replacing an existing div with another div using AJAX in ASP.NET

I am totally new to ASP.NET but good at Java, I need to know about how can I update an div with a new div (the div element can have some text inside it, want to change). I am learning ASP.NET to my own so I have tried my best to do so far! lets suppose my Default.aspx page has a div as:

          <head runat="server">
        <title>Untitled Page</title>
        <script
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

        <script type="text/javascript">

        function change(){
                $.ajax({
                    type: "GET",
                    url: "temp.aspx/Hello",
                    dataType: "html",
                    success: function(msg) {
                        console.log(msg);
                        $("#changer").html(msg);
                    }
                });
            }
            </script>
    </head>
    <body>
        <form id="form1" runat="server">
                <div id="changer">
                    <asp:Label ID="country" runat="server">USA</asp:Label>
                </div>
                    <input type="button"id="but" value="Hello Changer" onclick="change()"/>

        </form>
    </body>

I want to change the div with id=changer! Lets suppose that my temp.aspx page is as follow:

         <body>
            <form id="form1" runat="server">
            <div>
               Hello Text <asp:Label ID="lab" runat="server"></asp:Label>
            </div>
            </form>
        </body>

So the temp.aspx.cs would be:

[WebMethod]
public static String Hello()
{
    try
    {
        //Do here server event  
        System.Diagnostics.Debug.WriteLine("SomeText ");
         //this method is not called by the AJAX for some of my blunder, I don't even know
         //because if its called by the AJAX code the out will show SomeText string in output console!
        return " Hello";
    }
    catch (Exception)
    {
        throw;
    }
}

so the problem is how can I call the web method from the AJAX code because that I am learning ASP.NET to my own can somebody help me out of it thanks in advance!

Upvotes: 1

Views: 643

Answers (1)

joe_young
joe_young

Reputation: 4125

I don't know much about ASP.NET, but with AJAX and jQuery you can do this:

$("#changer").load("new_div.html");

This will load the file new_div.html into the #changer div


And if there is a specific div in the new_div.html file, you can load just this div by adding its id to the jQuery AJAX call:

$("#changer").load("new_div.html#content");

This will load only

<div id="content">
    Content...
</div>

From the new_div file

Upvotes: 2

Related Questions