Client Callback Javascript 傳值給 C#

摘要:Client Callback Javascript 傳值給 C#

CS檔
該類別需實作該介面ICallbackEventHandler 的方法

#region ICallbackEventHandler 成員

    public string GetCallbackResult()
    {
        return "成功";
    }
    string path = @"D:\display.txt";
    public void RaiseCallbackEvent(string eventArgument)
    {
        string startTime = eventArgument.Substring(0, eventArgument.IndexOf('-'));
       
        string endTime = eventArgument.Substring(eventArgument.IndexOf('-')+1, eventArgument.Length - eventArgument.IndexOf('-')-1);

        using (StreamWriter sw = new StreamWriter(path, true))
        {
            sw.Write(Environment.NewLine + "UID: " + PID + "  " + "StartTime:" + startTime + "  EndTime:" + endTime + "   " + (DateTime.Parse(endTime) - DateTime.Parse(startTime)) +"  "+eventArgument);
        }

    }

    #endregion

在Page_Load事件時

string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "getTime", "context"); //第三個參數為JavaScript函式傳回值的方法
        string callbackScript;
        callbackScript = "function CallServer(arg, context)" + "{ " + cbReference + ";}";  //arg為傳回的內容 由RaiseCallbackEvent方法中之參數 eventArgument
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

JavaScript語法

function getTime() {
            CallServer(startTime + "-" + endTime, ""); //傳回的值存於此
        }