在ASP.NET Web Forms中使用$ .ajax进行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变量。

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

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

您无法正确发送数据。对于“X WWW的窗体-urlencoded”键入字符串应该是以下格式:

​​

因为它不是,该方法的Request.Form不被给定在它期望的格式的数据。