【问题标题】:Avoid having to pass POST parameters in the URL using JQuery避免使用 JQuery 在 URL 中传递 POST 参数
【发布时间】:2016-12-21 23:39:09
【问题描述】:

请您帮我弄清楚为什么我似乎无法使用 data 参数传递数据,而必须使用 URL。

我在这里是一个相对较新的开发人员,所以也许这更多的是我不知道谷歌什么 - 但我很确定以下不是通过网络将数据获取到我的数据库的好方法API。这是我尝试修改的来自 asp.NET 的示例,但成功有限。使用其他两种方法中的任何一种都无法到达我的 Controller 类。

任何关于为什么下面两个评论部分不起作用的想法将不胜感激。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Product App</title>
    <meta charset="utf-8"/>
</head>
<body>
    <div>
        <h2>All Products</h2>
        <ul id="products"/>
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product"/>
    </div>
    <div>
        <h2>Add Product</h2>
        <form>
            ID:<br>
            <input type="number" id="setProdId" size="5"/><br>
            Name:<br>
            <input type="text" id="setProdName" size="10"/><br>
            Category:<br>
            <input type="text" id="setProdCategory" size="10"/><br>
            Price:<br>
            <input type="number" id="setProdPrice" size="10"/><br><br>
            <input type="button" value="Add" onclick="create();"/>
            <p id="setProduct"/>
        </form>
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
    var uri = 'api/products';

    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
          });
    });
    function formatItem(item)
    {
      return item.Name + ': $' + item.Price;
    }

    function find()
    {
      var id = $('#prodId').val();
      $.getJSON(uri + '/' + id)
          .done(function (data) {
            $('#product').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
          });
    }



    function create() {

        var settings = {
            "url": uri + "?id=" + $('#setProdId').val() + "&name=" + $('#setProdName').val() + "&category=" + $('#setProdCategory').val() + "&Price=" + $('#setProdPrice').val() + "",
            "method": "POST",
        }

        $.ajax(settings).done(function (response) {
            console.log(response)
        });

        //  $.ajax({
        //    method: "POST",
        //    url: uri,
        //    data: { id: $('#setProdId').val(), name: $('#setProdName').val(), category: $('#setProdCategory').val(), price: $('#setProdPrice').val() },
        //    contentType: "application/json",
        //    dataType: 'json'
        //});

        //    $.post(uri,
        //        {
        //            $('#setProdId').val(),
        //            $('#setProdName').val(),
        //            $('#setProdCategory').val(),
        //            $('#setProdPrice').val()
        //        }
        //    );
        //};
    }

   </script>
</body>
</html>

下面是控制器:

using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;{

        bool isSuccess = false;
        string connectionString = "my connection string";


        public int RetrieveProductsCount()
        {
            int count = 0;

            string strCount = "";

            using (SqlConnection myConnection = new SqlConnection())
            {
                myConnection.ConnectionString = connectionString;
                string oString = "SELECT COUNT(ID) as Count FROM tblProduct";
                myConnection.Open();
                SqlCommand oCmd = new SqlCommand(oString, myConnection);

                using (SqlDataReader oReader = oCmd.ExecuteReader())
                {
                    while (oReader.Read())
                    {
                        strCount = oReader["Count"].ToString();
                    }

                    try
                    {

                        isSuccess = int.TryParse(strCount, out count);
                        Console.WriteLine("Count of Products: " + count);

                    }
                    catch (System.FormatException e)
                    {
                        Console.WriteLine(e.Message);
                    }

                }
                myConnection.Close();
            }

            return count;

        }

        Product[] products = new Product[]
        {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };

        public IEnumerable<Product> GetAllProducts()
        {
            string sqlCommand = "SELECT * FROM tblProduct";
            DataSet ds = new DataSet();
            List<Product> productList;

            using (SqlCommand cmd = new SqlCommand(sqlCommand, new SqlConnection(connectionString)))
            {
                cmd.Connection.Open();
                DataTable table = new DataTable();
                table.Load(cmd.ExecuteReader());
                ds.Tables.Add(table);

                productList = new List<Product>();
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    Product product = new Product();
                    product.Id = Convert.ToInt32(table.Rows[i]["ID"]);
                    product.Name = table.Rows[i]["Name"].ToString();
                    product.Category = table.Rows[i]["Category"].ToString();
                    product.Price = Convert.ToDecimal(table.Rows[i]["Price"]);
                    productList.Add(product);
                }

                cmd.Connection.Close();
            }

            products = productList.ToArray();

            return products;
        }

        public IHttpActionResult GetProduct(int id)

        {

            string sqlCommand = "SELECT TOP(1) * FROM tblProduct WHERE ID =" + id.ToString();
            DataSet ds = new DataSet();
            Product lProduct = new Product();

            using (SqlCommand cmd = new SqlCommand(sqlCommand, new SqlConnection(connectionString)))
            {
                cmd.Connection.Open();
                DataTable table = new DataTable();
                table.Load(cmd.ExecuteReader());
                ds.Tables.Add(table);

                if (table.Rows.Count > 0)
                {
                    lProduct.Id = Convert.ToInt32(table.Rows[0]["ID"]);
                    lProduct.Name = table.Rows[0]["Name"].ToString();
                    lProduct.Category = table.Rows[0]["Category"].ToString();
                    lProduct.Price = Convert.ToDecimal(table.Rows[0]["Price"]);
                }

                else lProduct = null;

                cmd.Connection.Close();

            }

            //var product = products.FirstOrDefault((p) => p.Id == id);
            if (lProduct == null)
            {

                return NotFound();

            }

            return Ok(lProduct);


        }

        [HttpPost]
        public IHttpActionResult Create(int id, string name, string category, decimal price)
        {

            string sqlCommand = "INSERT INTO tblProduct (Id, Name, Category, Price) VALUES (@id, @name, @category, @price)";

            using (SqlCommand cmd = new SqlCommand(sqlCommand, new SqlConnection(connectionString)))
            {
                cmd.Connection.Open();

                cmd.Parameters.AddWithValue("@id", id);
                cmd.Parameters.AddWithValue("@name", name);
                cmd.Parameters.AddWithValue("@category", category);
                cmd.Parameters.AddWithValue("@price", price);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                }
                cmd.Connection.Close();

            }

            return Ok();
        }

    }
}
using System.Web.Http;

namespace ProductsApp.Controllers
{
    public class ProductsController : ApiController

【问题讨论】:

  • 您的$.ajax 调用对我来说看起来不错,因此可能是服务器端没有读取请求正文而仅读取查询字符串参数的问题。
  • 向我们展示您的控制器操作。
  • 非常感谢您的回复,我已将 Controller 类添加到上面的原始帖子中。

标签: jquery html asp.net ajax


【解决方案1】:

你的控制器期望 Post 方法

[HttpPost]
public IHttpActionResult Create(int id, string name, string category, decimal price)

但是您发送了 GET 请求,因为 $.getJson 使用 GET HTTP 请求从服务器加载 JSON 编码的数据。

只需按照您的评论使用您的 $.ajax 请求,但在 Controller 中使用正确的方法。

还有一点 我发现您仅为控制器 Create 定义动词,但 uri 请求产品。 在 MVC 的情况下修复该用法:

 $.ajax({
            url: "@Url.Action("Create", "api")",
            method: "POST",
            ... //Rest of your code

最后一点,如果您需要 JSON,只需再次从控制器返回 JsonResult 以防 MVC。

[HttpPost]
public JsonResult Create(int id, string name, string category, decimal price)
{
   //your code
    return Json(new { total = products.Count, records = products}, JsonRequestBehavior.AllowGet);
}

更新

我会解释的。

var uri = 'api/products';

$(document).ready(function () {
  // Send an AJAX request
  $.getJSON(uri)
      .done(function (data) {
        // On success, 'data' contains a list of products.
        $.each(data, function (key, item) {
          // Add a list item for the product.
          $('<li>', { text: formatItem(item) }).appendTo($('#products'));
        });
      });
});

这部分:需要 GET 动词来操作 products 但您在控制器中没有此操作。

这部分:

function find()
{
  var id = $('#prodId').val();
  $.getJSON(uri + '/' + id)
      .done(function (data) {
        $('#product').text(formatItem(data));
      })
      .fail(function (jqXHR, textStatus, err) {
        $('#product').text('Error: ' + err);
      });
}

再次使用了错误的操作,但几乎是正确的语法。

 $.getJSON('Api/GetProduct', {id: id})

这应该可行。

附言在需要动词的情况下,我在早期回复中的第一点可能不清楚。我很困惑,因为您只定义了一个 uri,但在不同的地方使用它可以访问不同的操作

【讨论】:

  • 非常感谢您的回答,非常感谢。您是否介意为我澄清几点:“只需按照您的评论使用您的 $.ajax 请求,但在 Controller 中使用正确的方法。” - 我不确定我是否理解正确的方法是什么在这种情况下。此外,这一行: url: "@Url.Action("Create", "api")" 在 VS 2015 中似乎没有解析,它似乎脱离了字符串。任何与这些有关的帮助表示感谢。
  • var uri = 'api/products'; 表示控制器/操作。我没有找到行动呼吁产品。 @Url.Action 行在最新更新的 VS 2015 中对 MVC5 没有正确的行为。这是已知问题
猜你喜欢
  • 2014-04-08
  • 1970-01-01
  • 2014-04-08
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
相关资源
最近更新 更多