【发布时间】: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 类添加到上面的原始帖子中。