javascript调用C#后台程序执行查询

目的:在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

         

            成长

       /      |     \

    学习   总结   分享

QQ交流群:122230156

原文地址:https://www.cnblogs.com/benio/p/2136308.html