【发布时间】:2018-12-11 15:55:59
【问题描述】:
在将值从 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);
}
});
});
});
获取值并将该参数(@LvlName)发送到数据库的WebMethod:
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
//string strMsg = "";
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdProc = new SqlCommand("InsertLvlName", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("@LvlName", lvl);
cmdProc.ExecuteNonQuery();
//strMsg = "Saved successfully.";
}
catch
{
}
finally
{
connection.Close();
}
return;
}
我需要帮助来检查两件事: 1)查看文本框是否为空,如果是这种情况,则不要将值保存到数据库中,并显示该字段需要具有某种值的警报。
2) 我需要检查某个字段的相同值是否已经在数据库中,然后不要保存它。
提前致谢!
【问题讨论】:
标签: c# jquery ajax webmethod insert-update