Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make client side click event handler to request a server side method
    text
    copied!<p>In details: I load HTML code onto the page and upon click of an <code>&lt;a&gt;</code> link, I want this click event to be captured and handled by the code-behind.</p> <p>Here is what I've got as client-side code:</p> <pre><code>$('a').click(function (e) { event.preventDefault(); var data = { userName: $(this).attr("id") }; var dataVal = JSON.stringify(data); $.ajax({ type: "POST", url: "Default.aspx/loadNewPage", contentType: "application/json; charset=utf-8", data: dataVal, dataType: "json", success: function (id) { } }); }); </code></pre> <p>HTML:</p> <pre><code>&lt;a href="#" id="kontakt"&gt;Go to Kontakt&lt;/a&gt; </code></pre> <p>The problem is that the code-behind function is not called, but just the <code>#</code> is added to the url...</p> <p>I'd much appreciate corrections on my code with code examples and maybe explanation on them. </p> <p><strong>UPDATE:</strong> tried with ASP page webmethods. Code-behind:</p> <pre><code>[WebMethod] public string loadNewPage(string id) { ltlContentCenter.Text = getPageCenter("kontakt"); ltlContentSide.Text = getPageSide("kontakt"); return "hello"; } </code></pre> <p>JS code:</p> <pre><code>function loadMe() { PageMethods.loadNewPage("kontakt", CallSuccess, CallError); } function CallSuccess(res) { alert(res); } function CallError() { alert('Error'); } </code></pre> <p>the HTML:</p> <pre><code> &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:ScriptManager ID="scpt" runat="server" EnablePageMethods="true" /&gt; &lt;div id="parent"&gt; &lt;div id="mainmenu"&gt; &lt;asp:LinkButton ID="LinkButton1" Text="FORSIDEN" CommandArgument="forsiden" OnCommand="loadPage_Command" runat="server" /&gt; &lt;br /&gt; &lt;asp:LinkButton ID="LinkButton2" Text="PRODUKTER" CommandArgument="produkter" OnCommand="loadPage_Command" runat="server" /&gt; &lt;br /&gt; &lt;asp:LinkButton ID="linkPages" Text="SUPPORT" CommandArgument="media" OnCommand="loadPage_Command" runat="server" /&gt; &lt;br /&gt; &lt;asp:LinkButton ID="LinkButton3" Text="KONTAKT" CommandArgument="kontakt" OnCommand="loadPage_Command" runat="server" /&gt; &lt;br /&gt; &lt;asp:LinkButton ID="LinkButton4" Text="OM ABiX" CommandArgument="omabix" OnCommand="loadPage_Command" runat="server" /&gt; &lt;br /&gt; &lt;/div&gt; &lt;div id="logo"&gt; &lt;/div&gt; &lt;asp:Literal ID="ltlContentCenter" runat="server" /&gt; &lt;asp:Literal ID="ltlContentSide" runat="server" /&gt; &lt;a href="#" onclick="loadMe()"&gt;Click Me, please.&lt;/a&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>The browser console gives me error <code>"PageMethods is not defined"</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload