【发布时间】:2014-08-21 01:06:31
【问题描述】:
我使用 Microsoft Visual Studio 2012 作为平台,并创建了 Web 表单项目 我在他的“表”文件夹中创建了数据库文件“SimpleDB.mdf”我添加了名为“表”的新表,它有两列 - id 和名称(字符串)。我试图将字符串数据插入到名称列中从 javascript 函数调用服务器端函数时的表。
这是 aspx.cs 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static string InsertData(string ID){
string source = "Data Source=(LocalDB)\v11.0;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
{
SqlCommand cmd = new SqlCommand("Insert into Table(Name) values('" + ID + "')", con);
{
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
}
这是aspx代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ProjectWWW.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function CallMethod() {
PageMethods.InsertData("hello", CallSuccess, CallError);
}
function CallSuccess(res) {
alert(res);
}
function CallError() {
alert('Error');
}
</script>
</head>
<body>
<header>
</header>
<div class="table" id="div1" > </div>
<form id="Form1" runat="server">
<asp:Button id="b1" Text="Submit" runat="server" onclientclick="CallMethod();return false;"/>
<asp:ScriptManager enablepagemethods="true" id="ScriptManager1" runat="server"></asp:ScriptManager>
</form>
</body>
</html>
所以基本上我期待单击按钮提交时,表列“名称”将填充“Hello”,但没有任何反应,该列保持为空(NULL)
【问题讨论】:
-
保持
Null是什么意思?您是要Update现有记录还是Insert新记录? -
我确实使用您的代码进行了测试,它正在使用更改 sql 查询作为:“插入 [表](名称)值('”+ ID +“')”。将 cmd.ExecuteNonQuery() 的 try-catch 并存储结果;在 int 变量中检查是否有任何错误。
标签: c# javascript asp.net sql sql-server