簡體   English   中英

如何通過ajax調用的c#函數更改asp標簽的文本

[英]How can I change the text of asp label through c# function which is called by ajax

我想通過ajax訪問asp控件。 說明:我想通過ajax調用c#函數。 此c#函數將更改具有不同條件的多個標簽文本。

請檢查以下代碼。

    <input id="btnSilverGetPrice2" class="btn btn-next btn-fill btn-success btn-wd" type="button" value="Get Price" />

    <script type="text/javascript">
        function CheckCode(val) {
            $.ajax({
                type: "GET",
                url: "Premium-Membership.aspx/FCheckCode",
                data: { 'name': val },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

        $("#btnSilverGetPrice2").click(function () {
            CheckCode();
        })    

        function OnSuccess(response) {
            alert(response.d);
        }
    </script>

C#代碼

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public static string FCheckCode()
    {
        Main_Website_SignIn obj = new Main_Website_SignIn();
        string ans=obj.trial();
        return ans;
    }

    public string trial()
    {
        try
        {
            if (Session["LUSER"].ToString() == "Jobseeker")
            {
                if (DropDownListSilver.SelectedValue == "6")
                {
                    lblShowRegularPrice.Text = "500/6 Months";
                    lblShowPopularPrice.Text = "1000/6 Months";
                    lblShowPlatinumPrice.Text = "1500/6 Months";

                    lblSilverPrice.Text = "500";
                    lblGoldPrice.Text = "1000";
                    lblPlatinumPrice.Text = "1500";
                }
             }
         }
         catch (Exception){}
         return "working";      
     }

消息成功返回,但標簽文本未更改。

我想通過ajax訪問asp控件。 說明:我想通過ajax調用c#函數。 此c#函數將更改具有不同條件的多個標簽文本。

網頁進入用戶瀏覽器后,ASP(通常是.Net)已超出范圍 .Net不再可以訪問控件。 本質上,操作順序如下:

  1. 請求開始。
  2. 您所有的.Net代碼都將執行,您可以在其中設置控件,例如,設置myLabel.Text的值
  3. .Net將控件轉換為HTML字符串 此時,它使用值(例如myLabel.Text )來生成HTML。
  4. HTML返回到瀏覽器,由瀏覽器顯示。
  5. 請求結束。

使用ajax時,您正在瀏覽器中執行操作。 您正在使用生成的HTML內容,而不是曾經用於生成HTML的ASP.Net控件。

問題的簡短答案是你不能這樣做 對於瀏覽器內操作,您需要一個瀏覽器內解決方案。 通過Javascript / jQuery分配值。 例如:

function OnSuccess(response) {
    $("#myLabel").text(response.foo);
    $("#myOtherLabel").text(response.bar);
    $("#myOtherOtherLabel").text(response.baz);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM