如何在不重新加载页面的情况下调用c#方法?

时间:2018-08-09 18:25:18

标签: c# asp.net

我在引导程序模式中有一个asp:LinkBut​​ton,我想使用它调用我在c#代码中拥有的方法,该方法将SOAP请求发送到远程服务器,然后以新的模式显示数据。问题是,当我单击按钮时,页面会重新加载,从而关闭第一个模态并阻止第二个模态弹出。如何在不重新加载页面的情况下调用c#方法?

Asp按钮代码:

<asp:LinkButton runat="server" ID="btnLMILink" OnClick="btnLogMeIn_ServerClick" OnClientClick="return false" CssClass="btn btn-primary btn-sm">click</asp:LinkButton>
按钮正在调用的

C#方法

protected void btnLogMeIn_ServerClick(object sender, EventArgs e)
{
        string lmiDivHTMLStart = "<div class=\"form-group\">";
        StringBuilder lmiDivHTMLMiddle = new StringBuilder();
        string lmiDivHTMLEnd = "</div>";
        List<string> lmiData = new List<string>();
        lmiData = GetLMIData();

        foreach(string str in lmiData)
        {
            lmiDivHTMLMiddle.Append("<label>"+str+"</label>");
        }

        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showLMIModal();", true);
        LMI_Div.InnerHtml = lmiDivHTMLStart + lmiDivHTMLMiddle + lmiDivHTMLEnd;
    }

以防万一,这是我的SOAP请求:

protected List<string> GetLMIData()
    {
        string url = "fake url";
        string companyID = "123456";
        string password = "fake password";
        string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(companyID + ":" + password));
        List<string> lmiData = new List<string>();
        string currentLine = "";

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Headers.Add(@"SOAP:Action");
        webRequest.ContentType = "application/json; charset=\"utf-8\"";
        webRequest.Accept = "application/json";
        webRequest.Method = "GET";
        webRequest.Headers.Add("Authorization", "Basic " + encoded);
        System.Diagnostics.Debug.WriteLine("web request created");

        try
        {
            System.Diagnostics.Debug.WriteLine("inside of try");
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);

            System.Diagnostics.Debug.WriteLine("reader and data stream created");
            while (!reader.EndOfStream)
            {
                System.Diagnostics.Debug.WriteLine("inside of while");
                currentLine = reader.ReadLine();              
            }
            System.Diagnostics.Debug.WriteLine("end of while");
            reader.Close();
            dataStream.Close();
            response.Close();
        }
        catch (HttpException ex)
        {

        }
        lmiData = SplitString(currentLine);
        System.Diagnostics.Debug.WriteLine("end of method");
        return lmiData;
    }

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:0)

您必须使用AJAX和WebMethod / Web服务来解决您的需求。为了解决当前情况,您必须进行以下更改:

  1. 将您的服务器端LinkBut​​ton“ btnLMILink”替换为普通锚标签(非服务器端)
  2. 创建一个WebMethod并将您的“ btnLogMeIn_ServerClick”代码放入其中
  3. 单击锚标记,对WebMethod进行AJAX调用

现在是解释:

  1. 替换LinkBut​​ton

从此:

<asp:LinkButton runat="server" ID="btnLMILink" OnClick="btnLogMeIn_ServerClick" OnClientClick="return false" CssClass="btn btn-primary btn-sm">click</asp:LinkButton>

对此:

<a id="btnLMILink" href="javascript:void(0)" class="btn btn-primary">btnLMILink</a>
  1. 创建一个WebMethod

我制作了一个名为“ PostMessage”的WebMethod,并将其中的“ btnLogMeIn_ServerClick”代码放入其中。随心所欲命名。我将静态数据放入“ lmiData”列表中;您可以在那里调用SOAP方法。

[WebMethod]
public static string PostMessage()
{
    var lmiDivHTMLStart = "<div class='form-group'>";
    var lmiDivHTMLMiddle = new StringBuilder();
    var lmiDivHTMLEnd = "</div>";
    var lmiData = new List<string>() { "Apple", "Android", "Mango", "Orange" }; // call SOAP method here

    foreach (string str in lmiData)
    {
        lmiDivHTMLMiddle.Append("<label>" + str + "</label>");
    }

    return lmiDivHTMLStart + lmiDivHTMLMiddle + lmiDivHTMLEnd;
}
  1. 拨打AJAX通话

第二个模式,我将其命名为“ soapModal”

<div class="modal fade" id="soapModal" tabindex="-1" role="dialog" aria-labelledby="myModal-label">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModal-label">Second Modal</h4>
            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save</button>
            </div>
        </div>
    </div>
</div>

调用WebMethod“ PostMessage”的AJAX方法。这里有一个名为“ Default.aspx”的页面,其中存在我的WebMethod,您可以根据页面和路径指定URL。

<script>

    $(function () {
        $('#btnLMILink').on('click', function () {

            $.ajax({
                type: 'POST',
                url: 'Default.aspx/PostMessage',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify({}),
                beforeSend: function () {
                    console.log('sending'); // show loader or something
                },
                success: function (result) {                        
                    $('#soapModal .modal-body').empty();
                    $('#soapModal .modal-body').append(result.d);
                    $('#soapModal').modal('show');
                },
                error: function (result) {
                    console.log('error');   // show error if not able to call WebMethod
                }
            });

        });
    });

</script>

我假设您的项目中包含jQuery。

希望有帮助