目的:在aspx頁面的一個文字框失去焦點時,觸發一個查詢TABLE的動作。
1. page_load 添加 txtInternal.Attributes["onfocus"] = "MyJsFunc()";
2. 頁面javascript添加:
<script ...>
...
function MyJsFunc() { var txt = document.getElementById("txtLotID").value; PageMethods.MyMethod(txt,OnSuccess); } function OnSuccess(value) { document.getElementById("txtInternal").innerText=value; //$get('<%= Label1.ClientID %>').innerText = result=="false" ? "該使用者登入" : "OK";
}
...
<script>
3. html添加:在div標籤裡頭,form外頭
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<form>
</form>
</div>
4.aspx.cs檔案:
[System.Web.Services.WebMethod] //要在用戶端使用伺服器方法,必須加上這個Attribute public static string MyMethod(string str_lotid) //方法必須是static { LabelView labelview = new LabelView(); labelview.LotID = str_lotid; HttpResponse resp = System.Web.HttpContext.Current.Response; ProcessGetLabelViewByLotID getLabelbylotid = new ProcessGetLabelViewByLotID(); getLabelbylotid.LabelView = labelview; try { getLabelbylotid.Invoke(); } catch (Exception ex) { string str_url; str_url = "ErrorPage.aspx?ErrorMessage=" + HttpUtility.UrlEncode(ex.Message);//Server.urlencode(ex.Message); resp.Redirect(str_url); } string str = getLabelbylotid.LabelView.PartName.ToString(); return str;
}
備忘:一定要有OnSuccess