繁体   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