我正在使用ASP,我想在不刷新页面的情况下将一些数据插入数据库,因此使用ajax。 但由于某些原因,我无法识别,数据不会被插入。
我的index.aspx:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtDesc" runat="server"></asp:TextBox>
</div>
</form>
<a href="#" id="btnInsert" onclick="insertData()">INSERT</a>
<script>
function insertData() {
var name = document.getElementById("txtName").value;
var description = document.getElementById("txtDesc").value;
alert(name + description);
$.ajax(
{
type: "POST",
url: "insertAjax.aspx/Insert",
data: "{'name':'" + name + "','description':'" + description + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function () { alert("Inserted"); },
error: function () { alert("Not inserted"); }
});
}
</script>
insertAjax.aspx
public partial class insertAjax : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Insert(string name, string description) {
using (ProductDataContext db = new ProductDataContext()) {
Product dt = new Product();
dt.Name = name;
dt.Description = description;
db.Products.InsertOnSubmit(dt);
db.SubmitChanges();
}
}
}
Product.dbml(使用linq to SQL):
ID int (primary key, auto increment)
Name varchar(255)
Description varchar(255)