详细信息:我将HTML代码加载到页面上,点击<a>
链接后,我希望此代码事件能够被代码隐藏捕获并处理。
以下是我作为客户端代码所拥有的内容:
$('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) {
}
});
});
HTML:
<a href="#" id="kontakt">Go to Kontakt</a>
问题是代码隐藏功能没有被调用,只是#
被添加到网址...
我非常感谢使用代码示例对代码进行更正,并对其进行解释。
更新 尝试使用ASP页面webmethods。代码隐藏:
[WebMethod]
public string loadNewPage(string id)
{
ltlContentCenter.Text = getPageCenter("kontakt");
ltlContentSide.Text = getPageSide("kontakt");
return "hello";
}
JS代码:
function loadMe() {
PageMethods.loadNewPage("kontakt", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
HTML:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scpt" runat="server" EnablePageMethods="true" />
<div id="parent">
<div id="mainmenu">
<asp:LinkButton ID="LinkButton1" Text="FORSIDEN" CommandArgument="forsiden" OnCommand="loadPage_Command"
runat="server" />
<br />
<asp:LinkButton ID="LinkButton2" Text="PRODUKTER" CommandArgument="produkter" OnCommand="loadPage_Command"
runat="server" />
<br />
<asp:LinkButton ID="linkPages" Text="SUPPORT" CommandArgument="media" OnCommand="loadPage_Command"
runat="server" />
<br />
<asp:LinkButton ID="LinkButton3" Text="KONTAKT" CommandArgument="kontakt" OnCommand="loadPage_Command"
runat="server" />
<br />
<asp:LinkButton ID="LinkButton4" Text="OM ABiX" CommandArgument="omabix" OnCommand="loadPage_Command"
runat="server" />
<br />
</div>
<div id="logo">
</div>
<asp:Literal ID="ltlContentCenter" runat="server" />
<asp:Literal ID="ltlContentSide" runat="server" />
<a href="#" onclick="loadMe()">Click Me, please.</a>
</div>
</form>
</body>
浏览器控制台错误"PageMethods is not defined"
。
答案 0 :(得分:2)
Ok ..不是jquery方式,而是使用客户端脚本访问服务器端的更多c#方式。尝试使用page methods
首先在aspx页面上添加一个脚本管理器
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scpt" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
</form>
</body>
然后转到aspx.cs页面并声明类似
的函数[System.Web.Services.WebMethod]
public static string ValidateUser(string emailId, string password)
{
//Your logic code
return "hello from server side";
}
然后从你的javascript调用c#方法,如
PageMethods.ValidateUser(email, password, CallSuccess_Login, CallFailed_Login);
并且还在你的javascript中创建2个回调函数CallSuccess_Login和CallFailed_Login
希望有所帮助
答案 1 :(得分:1)
使用可以这样做:
$('a').click(function () {
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) {
alert("loaded");
}
});
});
[WebMethod]
public static void loadNewPage(int id)
{
// do the loading of the new HTML, etc.
}
您可以通过here了解有关Jquery AJAX调用的更多信息。