的URL POST參數,請您能不能幫我明白爲什麼我似乎不能使用數據參數的數據通過,而必須使用的URL。避免通過使用jQuery
我在這裏是一個相對較新的開發人員,所以也許這是對我而言更多的是失敗的知道什麼對谷歌 - 但我敢肯定,下面是不是通過獲取數據到我的數據庫的好方法Web API。這是我嘗試修改的asp.NET的一個例子,但成功有限。使用其他兩種方法都不能達到我的控制器類。
爲什麼兩個註釋的部分下面不工作任何想法,將不勝感激。
<!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'調用看起來好像沒什麼問題,所以它可能是不讀書的問題,服務器端請求正文並只讀取查詢字符串參數。 – Karin
向我們展示您的控制器操作。 – Jasen
非常感謝您的回覆,我已將Controller類添加到上面的原始帖子中。 –