【问题标题】:Check duplicate value in the database检查数据库中的重复值
【发布时间】: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


    【解决方案1】:

    这是我们可以使用 jquery 进行的简单验证

    if (inp.val().length > 0) {
        //do something
    }
    else
    {
    alert("Enter Value")
    }
    

    完整示例:-

     $(function () {
    
             $('#myButton').on('click', function () {
    
                 var lvl = $('#MainContent_txtProductConstruction').val()
                    if(lvl.length>0)
                    {
                 $.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);
                     }
                 });
                 }
                else
                {
                alert("Please enter Value")
                }
             });
    
         });
    

    第二部分:-

    SqlCommand checkvalue = new SqlCommand("SELECT COUNT(*) FROM [TableName] WHERE ([ColumnNameUser] = @user)" , connection);
    checkvalue.Parameters.AddWithValue("@user", lvl);
    int UserExist = (int)checkvalue.ExecuteScalar();
    
    if(UserExist > 0)
    {
       //Username exist
    }
    else
    {
       //Username doesn't exist.
    }
    

    Reference Link

    如果你想让 Sp 检查然后:-

    根据您的姓名和字段名称对其进行编辑。

    CREATE PROCEDURE InsertName
    (
      @username varchar(25), 
      @userpassword varchar(25)
    )
    AS
    IF EXISTS(SELECT 'True' FROM MyTable WHERE username = @username)
    BEGIN
      --This means it exists, return it to ASP and tell us
      SELECT 'This record already exists!'
    END
    ELSE
    BEGIN
      --This means the record isn't in there already, let's go ahead and add it
      SELECT 'Record Added'
      INSERT into MyTable(username, userpassword) VALUES(@username, @userpassword)
    END
    

    【讨论】:

    • 我认为我需要在 ajax 中这样做,所以如果没有值空字符串将不会保存在数据库中
    • 简单如果值存在 ajax 将调用其他简单提醒用户@freej17
    • 这适用于问题的第一部分,谢谢!
    • 找到第二部分也@freej17
    【解决方案2】:

    首先,您可能希望使用 jQuery 检查您的文本框是否为空,如果是,则不要触发对 web 方法的调用。请参阅Accessing Asp.net controls using jquery (all options) 从 jQuery 调用 asp.net 控件

    if ($('#<%= myTextBox.ClientID %>').val().length == 0) 
    {
       alert("Text Box is empty");
    }
    else
    {
        ///make ajax call to webmethod...
    }
    

    旁注如果用户在文本框中输入空格,您希望发生什么?

    接下来,您可以调用插入或更新数据库中的记录,以免插入任何重复项。或者我可能想从数据库中选择所有数据,然后比较数据以查看文本框中的条目是否已经存在于数据库中。

    这里的答案应该会有所帮助c# update if record exists else insert new record

    这样的事情应该会给你你需要的结果:

    SqlCommand cmdCount = new SqlCommand("SELECT * from Table WHERE TextboxValue= @textBoxValue", myConnection);
    cmdCount.Parameters.AddWithValue("@textBoxValue", _textBoxValue);
    int count = (int)cmdCount.ExecuteScalar();
    
    if (count > 0)
    {
        ///Run Insert statement
    }
    

    【讨论】:

    • 我正在考虑在插入过程之前在存储过程中使用 IF EXIST。如果存在重复值,则发送某种错误并且不插入任何值?
    猜你喜欢
    • 2020-02-25
    • 2015-07-02
    • 1970-01-01
    • 2020-01-10
    • 2018-05-29
    • 2017-11-24
    • 2012-08-31
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多