使用javascript从后面的代码调用c#函数

时间:2016-10-06 09:49:44

标签: javascript c# web-services code-behind

我需要在我的代码中使用javascript调用c#函数,其中我设置了两个变量,我需要使用这些变量调用我的函数,遵循我的代码:

C#代码背后:

 public string CallWebMethod(string url, Dictionary<string, string> dicParameters)
{
    try
    {


        byte[] requestData = this.CreateHttpRequestData(dicParameters);
        HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.KeepAlive = false;
        httpRequest.ContentType = "application/json; charset=utf-8";
        httpRequest.ContentLength = requestData.Length;
        httpRequest.Timeout = 30000;
        HttpWebResponse httpResponse = null;
        String response = String.Empty;

        httpRequest.GetRequestStream().Write(requestData, 0, requestData.Length);
        httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        Stream baseStream = httpResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(baseStream);
        response = responseStreamReader.ReadToEnd();
        responseStreamReader.Close();

        return response;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
    StringBuilder sbParameters = new StringBuilder();
    foreach (string param in dic.Keys)
    {
        sbParameters.Append(param);//key => parameter name
        sbParameters.Append('=');
        sbParameters.Append(dic[param]);//key value
        sbParameters.Append('&');
    }
    sbParameters.Remove(sbParameters.Length - 1, 1);

    UTF8Encoding encoding = new UTF8Encoding();

    return encoding.GetBytes(sbParameters.ToString());

} 

这是我的javascript:

<script>

function SendNeedHelpLinkTrace() {

    var keysToSend = ['pCatchLinkVirement', 'pCatchLinkCarteBancaire', 'pCatchLinkRechargePaiementFactureTelecom', 'pCatchLinkPaiementVignetteImpotTaxe', 'pCatchLinkPaiementFactureEauElectricite', 'pCatchLinkServiceFatourati', 'pCatchLinkCihExpress', 'pCatchLinkEdocuments']

    var lChannelId = document.getElementById('<%= HiddenChannelId.ClientID%>').value;
    var lServiceId = "900149";
    var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;

    //alert(lClientId);

    var lData = keysToSend.reduce(function(p,c){
        var _t = sessionStorage.getItem(c);
        return isEmpty(_t) ? p : p + ' | ' + _t;
    }, '')


    function isEmpty(val){
        return val === undefined || val === null;
    }

    var lCollect;

        console.log(lClientId);

        console.log(lData);

        alert(lData);
         // this is the dictionnary:
        lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;

        console.log(lDataCollected);

        //this is the url:
        var url="http://10.5.230.21:4156/CatchEvent.asmx/CollectData";

         sessionStorage.clear();
      }

我该怎么办?

0 个答案:

没有答案