[英]Calling method from Master.cs on any aspx page using javascript on Master.Master
我想在網站(任何頁面)上停留30秒后為用戶提供折扣(彈出式窗口)。 由於此項目實現了WebForms母版頁,因此我將計時器放入Master.aspx中,並將與db通信的方法放入Master.cs中。 該方法通過調用存儲過程來檢查是否合格,並返回bool。
我在aspx母版頁中設置了javascript計時器,因此超時后,我想調用提供用戶ID的方法。 我如何使用JavaScript將此稱為Master.cs內部的isUserEligibleForDiscount方法?
setTimeout(function () {
if (sessionStorage.getItem('timer') == 'on') {
if (isUserEligibleForDiscount(userID)) {
$('#myModal').modal('show');
}
sessionStorage.setItem('timer', 'off');
}
}, 30000);
使用[WebMethod]
屬性。 它使方法可從遠程Web客戶端(WebMethodAttribute Class)調用。 使用該屬性裝飾您的isUserEligibleForDiscount
。
然后可以通過Ajax調用該方法。 您在URL中為Ajax調用指定頁面: 'yourpage.aspx/isUserEligibleForDiscount'
您可以將您的方法放到只保留代碼的頁面中,也可以調用asmx Web服務。
setTimeout(function() {
doAjaxPageMethodCall();
//if (sessionStorage.getItem('timer') == 'on') {
// if (isUserEligibleForDiscount(userID)) {
// $('#myModal').modal('show');
// }
// sessionStorage.setItem('timer', 'off');
//}
}, 3000);
function doAjaxPageMethodCall() {
$.ajax({
type: "POST",
// page-methods.aspx holds your methods.
// replace AjaxPageMethodCall w/ isUserEligibleForDiscount.
url: "/page-methods.aspx/AjaxPageMethodCall",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(data) {
if(data.d===true) {
// show modal .
}
}).fail(function() {
$("#lbl").html("Houston...");
});
}
當然,您可以結合使用這兩個功能,它們只是分開進行測試。
Web服務類似於:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="/web-services/test-service.asmx" />
</Services>
</asp:ScriptManager>
而對ajax調用的唯一更改是url:
url: "/web-services/test-service.asmx/HelloWorld", ...
您的test-service.cs文件將包含實際方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.