【发布时间】:2018-07-04 07:15:25
【问题描述】:
需要检查TextBox中的值是否已经在数据库中,如果没有则再次保存在数据库中。
这是文本框代码:
<tr>
<td>
<asp:Label ID="lblProductConstruction" runat="server" Text="Product Construction:" Font-Names="Open Sans"></asp:Label></td>
<td>
<asp:TextBox ID="txtProductConstruction" runat="server" Font-Names="Merriweather" margin-Left="100px" ></asp:TextBox><br />
</td>
</tr>
<tr>
保存按钮:
<input type="button" class="button" id="myButton" value="Save"/>
Ajax 按钮点击:
$(function () {
$('#myButton').on('click', function () {
var lvl = $('#MainContent_txtProductConstruction').val()
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({'lvl': lvl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Saved successfully.");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
});
});
获取值并将该参数(@ObjekatName)发送到数据库的WebMethod:
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
cmdCount.CommandType = CommandType.StoredProcedure;
cmdCount.Parameters.AddWithValue("@ObjekatName", lvl);
cmdCount.ExecuteNonQuery();
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
connection.Close();
}
else
{
SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("@ObjekatName", lvl);
cmdProc.ExecuteNonQuery();
//strMsg = "Saved successfully.";
}
}
catch
{
}
finally
{
connection.Close();
}
return;
第一个过程是一个尝试在数据库中查找值的选择。 如果此选择找到某些内容,则 Count 必须大于 0,这应该关闭连接。 如果 select 没有返回任何东西,则必须将这个新值插入到数据库中。
我已经执行并测试了这些存储过程,它们运行良好。 问题出在 C# 中,我认为我在这里做错了,这不能正常工作。 有人可以帮我处理 c# 部分吗? 顺便说一句:Ajax 工作正常,WebMethod 正确获取值
提前致谢!
【问题讨论】:
-
能否提供程序
-
找到了解决方案,谢谢!
-
那是什么问题???
-
当数据库中没有值时,它返回 NULL 并且此代码帮助 if (count == null) 然后插入新值。
-
在存储过程中你可以这样做
if exists(select * from table)begin select 1 end else begin select -1 end...记住 null 不是建议的方式...您可以轻松地在数据库中处理并且您编写的代码将按原样工作