![](/img/trans.png)
[英]ASP.NET textbox losing value after postback when value is changed client-side via javascript
[英]ASP menu : how to avoid postback and access the selected value with a Javascript client side script
我必須實現一種從 ASP 水平菜單(使用配置文件生成)中選擇值的方法。 菜單的生成不是問題:我的實際問題是找到一種方法讓用戶在不使用回發的情況下訪問其值。
我正在處理一個大而舊的項目,該項目的編碼目的是根本不使用 PostBack 請求。 回發在設計上是意外的,被視為錯誤。
為了達到我的目標,我嘗試為以 return false 結尾的 MenuItemClick 事件編寫一個 JavaScript 觸發器,以避免回發(目前 JavaScript 代碼僅限於簡單的測試警報和 false 返回,用於測試目的) . 但這不起作用:我無法讓事件觸發 JavaScript 函數:發生回發,這是不希望的。
完整的代碼由數千行組成(其中大部分與問題無關),這里是一個只有相關行的刪節版本:
默認.aspx:
<%@ Register TagPrefix="CRB" Namespace="ConfigurableReportBuilder.PageControls" Assembly="ConfigurableReportBuilder" %>
<form id="form1" class="page" runat="server">
<CRB:HorizontalMenu ID="MainMenu" runat="server" RootNode="Menu/Items" StyleClass="ui-menu ui-state-hover"/>
//this works fine, no issue here.
</form>
默認.aspx.cs:
(...)
if (this.IsPostBack)
throw new Exception("PostBack requests are not expected to occur");
//Ensure that "PostBack requests" (which are unexpected and therefore indicate bugs) become recognized by a specific exception which is thrown here
工作區.js:
var WS = (function ($) {
var test = function (event) {
alert("test");
return false; //prevent postback
};
(...)
return {// This dictionary contains references to public methods used in the project
test: test,
(...)
}
}
$(document).on("menuitemclick", '#MainMenu', WS.test); //setting the event trigger
我找到了一個確實達到預期目標的解決方案,但要注意,它不尊重編碼的良好做法。 可能有更好的解決方案可用,但我找不到任何解決方案。
這個想法是放棄基於 MenuItemClick 事件的邏輯並恢復為 ASP 菜單的默認行為,將 URL 作為可點擊的菜單項 (NavigateUrl)。 這些 URL 將可以在主頁中訪問而無需任何回傳,因此它們可以用於攜帶信息……作為小型 JavaScript 代碼。
為此,必須在菜單項初始化期間將原始 Javascript 代碼設置為 NavigateUrl 參數:
protected MenuItem getMenuItem(XmlNode menuNode)
{//function that initialize a MenuItem with an XML node as parameter
MenuItem mi = new MenuItem(); //creating a MenuItem object
//Assigning its properties:
mi.Text = menuNode.Attributes["text"].Value;
if (menuNode.Attributes["description"] != null)
mi.ToolTip = menuNode.Attributes["description"].Value;
if (menuNode.Attributes["configfile"] != null) {
mi.Value = menuNode.Attributes["configfile"].Value;
mi.NavigateUrl = "javascript:alert('"+mi.Value+"');"; //Note that this isn't an URL
}
}
因此,來自 ASP 菜單的 URL 不是鏈接,而是將在主頁中執行的函數,無需通過任何事件。 因此,這些函數可用於檢索所需的值,而無需通過任何回發事件:在我剛剛給出的示例中,一個警報窗口顯示所選的下拉值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.