Ajax:将输入框值传递给C#代码

时间:2014-04-28 10:10:34

标签: c# javascript jquery asp.net ajax

我的AJAX几乎正常工作。我可以让它执行一个简单的函数并返回一个值,如日期和时间。

我现在的问题是开发脚本以将输入框的值发送到C#函数,然后在代码中使用此值。这样就可以返回正确的字符串。

如果sombody可以检查我是做对了还是出错了那么那就太棒了

谢谢

Ajax代码

 $(document).ready(function ste() {
        // Add the page method call as an onclick handler for the div.
        $("#Result").click(function () {
            var thePostCode = $('#ContentPlaceHolder1__postCodeInput').val();
            $.ajax({
                type: "POST",
                url: "Add-Property.aspx/GetAverageRent",
                data: { PostCode: thePostCode },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // Replace the div's content with the page method's return.
                    $("#Result").text(msg.d);
                    alert("code was executed");
                    codeAddress();
                }
            });
        });
    });

C#功能代码

[WebMethod]
        public static string GetAverageRent(string PostCode)
        {
            string Postcode = PostCode;
                var webGet = new HtmlWeb();
                var doc = webGet.Load("http://www.webaddress.com" + Postcode);


                HtmlNode AvgPrice = doc.DocumentNode.SelectSingleNode("//div[@class='split2r right']//strong[@class='price big']");

                if (AvgPrice != null)
                {
                    return AvgPrice.InnerHtml.ToString();
                }
                else
                {
                    return "Invalid Postcode!";
                }
        }

标记

<div class="form-group">
                            <label for="_postCodeInput">Post Code: </label>
                            <input type="text" runat="server" id="_postCodeInput" onchange="ste()" class="form-control"/>
                            <asp:RequiredFieldValidator ID="_pcodeRFV" runat="server" Display="Dynamic" ControlToValidate="_postCodeInput" ValidationGroup="saveProperty" ErrorMessage="Property Postcode" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
                       <div id="Result">Click here for the time.</div>

0 个答案:

没有答案