在ASP.NET Web窗体中使用$ .ajax进行ajax调用

时间:2017-10-06 12:40:46

标签: c# jquery asp.net ajax asp.net-ajax

我正在尝试在我的示例程序中使用$.ajax方法。我设计了如下页面:

<form id="form1" runat="server">
        <div>
            Country:
            <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
            Title:
            <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
            <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />
            <div id="container"></div>
        </div>
        <script src="Scripts/jquery-1.10.2.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnAjax").click(function (evt) {
                    debugger;
                    var data = {};
                    data.country = $("#txtCountry").val();
                    data.title = $("#txtTitle").val();
                    $.ajax({
                        url: "PostTarget.aspx",
                        type: "POST",
                        data: data,
                        contentType: "x-www-form-urlencoded;charset=UTF-8",
                        dataType: "json",
                        success: SuccessfulAjaxResponse,
                        error: ErroticAjaxResponse
                    });
                    evt.preventDefault();
                });
            });
            function SuccessfulAjaxResponse(results, status, jqXHR) {
                $("#container").empty();
                for (var i = 0; i < results.length; i++) {
                    $("#container").append("<tr>" +
                        "<td>" + results[i].EmployeeID + "</td>" + 
                        "<td>" + results[i].FirstName + "</td>" + 
                        "<td>" + results[i].LastName + "</td>"
                        );
                }
            }

            function ErroticAjaxResponse(jqXHR, status, error) {
                alert("Error: " + status);
            }
        </script>
    </form>

PostTarget.aspx.cs 中的代码定义如下。

protected void Page_Load(object sender, EventArgs e)
{
    var country = Request.Form["country"];
    var title = Request.Form["title"];
    var db = new NORTHWNDEntities();
    var emps = db.Employees
        .Where(x => x.Country.Contains(country) || x.Title.Contains(title))
        .Select(x => new EmployeeSearchResult
    {
        EmployeeID = x.EmployeeID,
        FirstName = x.FirstName,
        LastName = x.LastName
    });
    Response.Clear();
    Response.Write(JsonConvert.SerializeObject(emps));
    Response.Flush();
    Response.End();
}

调试上述内容时,我没有将值转换为countrytitle变量。

验证了一些在线资源,但代码几乎相似。

如果我在任何地方做错了,有人可以检查并建议我吗?

1 个答案:

答案 0 :(得分:1)

您没有正确发送数据。对于'x-www-form-urlencoded'类型,字符串应采用以下格式:

country=countryName&title=titleName

但事实并非如此,Request.Form方法没有以预期的格式提供数据。