web api不调用jquery函数

时间:2015-02-26 12:43:00

标签: c# jquery asp.net json asp.net-web-api

我有一个web api,可以通过jquery在html页面输入数据时在表格中发布数据。 web api功能如下:

   public HttpResponseMessage Post(User user)
        {

            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

带有jquery脚本的html页面是:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <div>
    <h2>All users</h2>
    <ul id="users" />
  </div>

<div>
    <h2>Insert New User</h2>
    First Name : <input type="text" id="firstName"  /><br />
    Last Name : <input type="text" id="lastName"  /><br />
    City  : <input type="text" id="city"  /><br />
    Email : <input type="email" id="email"  /><br />
    Password : <input type="password" id="password"  /><br />
    Phone number:    <input type="number" id="phone"  /><br />
    <input type="button" id="btnsave" value="Save" onclick="Post();" />
    <p id="P1" />
  </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
      var uri = 'api/user';

      $(document).ready(function () {
          // Send an AJAX request
          getuserlist();
      });


      function getuserlist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#users').html('');
                 // On success, 'data' contains a list of users.
                 $.each(data, function (key, item) {
                     // Add a list item for the user.

                     $('<li>', { text: formatItem(item) }).appendTo($('#users'));
                 });
             });
      }
      function formatItem(item) {
          return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
      }

      function Post() {
          jQuery.support.cors = true;
          var source = {
              'firstName': $('#firstName').val(),
              'lastName': $('#lastName').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'city': $('#city').val(),
              'password': $('#password').val()
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/user",
              data: source,
              success: function (data) {
                  var strResult = "<table><th>Returned Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + source.email + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);
              },
              error: function (x, y, z) {

                  var strResult = "<table><th>Error Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + x.responseText + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);
                  // alert(x + '\n' + y + '\n' + z);
              }
              //success: function (data) {
              //    //alert(data);
              //    getuserlist();
              //    // alert(jQuery.parseJSON(data));

              //},
              //error: function (error) {
              //    jsonValue = jQuery.parseJSON(error.responseText);
              //    //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              //}
          });
      });
  </script>
</body>
</html>

当我点击按钮添加新用户时,post()函数无法正常工作。 页面保持不变,没有动作,没有错误。

请帮忙! 谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您要发布的网址应为"/api/user/Post"

<强>输出

enter image description here

我必须修复已发布的代码中的其他几个JavaScript错误。正如其他人在评论中提到的那样,这些错误显示在控制台中。了解如何使用开发人员工具进行调试是非常宝贵的,值得花时间学习它们。

以下是修正的更新代码:

  <div>
    <h2>All users</h2>
    <ul id="users" />
  </div>

<div>
    <h2>Insert New User</h2>
    First Name : <input type="text" id="firstName"  /><br />
    Last Name : <input type="text" id="lastName"  /><br />
    City  : <input type="text" id="city"  /><br />
    Email : <input type="email" id="email"  /><br />
    Password : <input type="password" id="password"  /><br />
    Phone number:    <input type="number" id="phone"  /><br />
    <input type="button" id="btnsave" value="Save" onclick="Post();" />
    <p id="P1" />
  </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
     var uri = 'api/user';

      $(document).ready(function () {
          // Send an AJAX request
          getuserlist();
      });


      function getuserlist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#users').html('');
                 // On success, 'data' contains a list of users.
                 $.each(data, function (key, item) {
                     // Add a list item for the user.

                     $('<li>', { text: formatItem(item) }).appendTo($('#users'));
                 });
             });
      }
      function formatItem(item) {
          return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
      }

      function Post() {
          jQuery.support.cors = true;
          var source = {
              'firstName': $('#firstName').val(),
              'lastName': $('#lastName').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'city': $('#city').val(),
              'password': $('#password').val()
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/user/Post",
              data: source,
              success: function (data) {
                  var strResult = "<table><th>Returned Message</th>";
                  $.each(data, function (index, data) {
                      strResult += "<tr><td> " + source.email + " </td></tr>"
                      strResult += "</table>";
                      $("#divResult").html(strResult);
                  });
              },
              error: function (x, y, z) {

                  var strResult = "<table><th>Error Message</th>";
                  $.each(x, function (index, data) {
                      strResult += "<tr><td> " + x.responseText + " </td></tr>"
                      strResult += "</table>";
                      $("#divResult").html(strResult);
                      // alert(x + '\n' + y + '\n' + z);
                  });
              }
              //success: function (data) {
              //    //alert(data);
              //    getuserlist();
              //    // alert(jQuery.parseJSON(data));

              //},
              //error: function (error) {
              //    jsonValue = jQuery.parseJSON(error.responseText);
              //    //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              //}
          });
      };
  </script>

我还假设您的User对象如下:

public class User
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    public string city { get; set; }
    public string password { get; set; }
}