首页 > 解决方案 > Get ID and Value from a checkbox: Return to model and use in method to insert into sql database

问题描述

我正在尝试创建一个复选框列表,用户应该能够根据选择选择一个或多个选项:这应该被插入到数据库表中,其中插入了选择的 id。(这是在用户可以“编辑车库”的页面上),因此garageid也应该被提取,并且garageid应该choice id将 和 都插入到我创建的交叉表中,如下所示:

   [ID]
  ,[GarageID]
  ,[RequestProperty]
  ,[CreatedDate]
  ,[CreatedBy]
  ,[UpdatedDate]
  ,[UpdatedBy]

我还有一个用于插入的存储过程:

ALTER PROCEDURE [dbo].[spGarageGetRequestTypes]
    -- Add the parameters for the stored procedure here

    @GarageID INT,
    @RequestType INT

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    INSERT INTO GarageCrossRequestType
    (GarageID, RequestProperty)
    VALUES (@GarageID, @RequestType)
    
END

“编辑页面”正在工作和运作,这也是我得到的地方garageId。它看起来如下所示:

<div class="form-group">
                <div class="row">
                    <label class="col-xs-2 control-label">Garage</label>
                    <input type="text" class="col-lg-10 form-control" name="GarageName" id="GarageName" placeholder="Name" required="" />
                </div>
            </div>
            <div class="form-group">
                <div class="row">
                    <label class="col-xs-2 control-label">Contact person</label>
                    <input type="text" class="col-lg-10 form-control" name="ContactPerson" id="ContactPerson" placeholder="ContactPerson" required="" />
                </div>
            </div>
            <div class="form-group">
                <div class="row">
                    <label class="col-xs-2 control-label">Email</label>
                    <input type="email" class="col-lg-10 form-control" name="Email" id="Email" placeholder="Email" required="" onblur="validateEmail(this.value);" /><p id="InvalidMeg" style="font-size: 25px; color: red">Invalid e-mail address</p>
                </div>
            </div>

<script type="text/javascript">
function editGarage(e) {
            e.preventDefault();
            var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
            var garageId = dataItem.GarageId;
            countryId = dataItem.CountryId;
        var email = dataItem.Email;
            var contactperson = dataItem.ContactPerson;
            if (garageId != 0) {
                $("#EditGarageBtn").show();
                $("#saveNewGarageBtn").hide();
                $("#GarageName").val(name);
                $("#Country").val(countryId);
                $("#ContactPerson").val(contactperson);
                $("#Email").val(email);
              
            }
        }

 $("#EditGarageBtn").click(function () {
            var customerNumber = customerNumberOfEditingGarage;

            name = $("#GarageName").val();
            countryId = $("#Country").val();
            var garageId = $("#garageId").val();
            var contactperson = $("#ContactPerson").val();
            var email = $("#Email").val();
            $("#EditGarageBtn").hide();

            if (name.length > 0 && email.length > 0 && contactperson.length > 0) {
            $.ajax({
                url: '@Url.Action("EditGarage", "Garage")',
                dataType: 'JSON',
                data: {
                    name: name, countryId: countryId, garageId: garageId, 
                    contactperson: contactperson, email: email
                },
                success: function (data) {
                    if (data == "Failure") {
                        toastr["error"]("Error editing Garage");
                    }
                    else {
                        toastr["success"]("Garage successfully updated");
                        customerNumberOfEditingGarage = null;
                        refreshGrid();
                    }
                },
                error: function () {

                }
            });
            } else {
                toastr["error"]("Error editing Garage");
            }
        });

</script>

模型:

 public class GarageModel
    {
        public int GarageTypeId { get; set; }
        public int CountryId { get; set; }
        public string ContactPerson { get; set; }
        public string Email { get; set; }
        public int GarageId { get; set; }


    // for the choices in the checkbox
    public int ScheduledService { get; set; } = 1;
        public int Tires { get; set; } = 2;
    }

方法:

public bool EditGarage(GarageModel model)
        {
            var valid = false;

            var cmd = new SqlCommand("spGarageEditGarage", Connection);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@GarageId", model.GarageId);
            cmd.Parameters.AddWithValue("@CountryId", model.CountryId);
            cmd.Parameters.AddWithValue("@Name", model.Name);
            cmd.Parameters.AddWithValue("@ContactPerson", model.ContactPerson);
            cmd.Parameters.AddWithValue("@Email", model.Email);
            try
            {

                int result = cmd.ExecuteNonQuery();
                if (result == 1)
                    valid = true;
            }

            catch (SqlException ex)
            {
                throw new Exception(ex.Message);

            }
            finally
            {
                Connection.Close();
            }


        // for the choices in the checkbox (not working!)
            List<int> newlist = new List<int>();
            newlist.Add(model.Tires);
            newlist.Add(model.ScheduledService);

            foreach (var item in newlist)
            {
                if (newlist != null)
                {
                    var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
                    cmd1.CommandType = CommandType.StoredProcedure;
                    cmd1.Parameters.AddWithValue("@GarageId", model.GarageId);
                    cmd1.Parameters.AddWithValue("@RequestType", newlist.First());

                    int result = cmd1.ExecuteNonQuery();
                    if (result == 1)
                        valid = true;
                }
            }

            return valid;
        }

如果您查看我在模型和方法中的评论,您可以看到我为我正在尝试实现的“选择”功能添加的内容。这也是我为输入类型创建的 html:

@foreach (var items in Model)
                    {
                        <div class='form-group' style="margin-left: 60%;">
                            <div class="row">
                                <label class="ab">Tires</label>
                                <input type="checkbox" class="checkbclass" name="@items.Tires" id="Tires" placeholder="Tires" required="" value="@items.Tires" />
                            </div>
                        </div>

                        <div class='form-group' style="margin-left: 60%;">
                            <div class="row">
                                <label class="ab">Scheduled Service</label>
                                <input type="checkbox" class="checkbclass" name="@items.ScheduledService" id="Scheduled" placeholder="Scheduled" required="" value="@items.ScheduledService" />

                            </div>
                        </div>
                    }

现在,对于问题:

1:我需要某种方法来确保选中了哪个或是否选中了复选框,并且需要以某种方式将其返回给模型或控制器。我只想返回它的数值,如模型中所示,我希望轮胎的数值为 2 等等。

  1. 数据库插入有效(所以至少是这样),但表只接受RequestPropertyand GarageID,这意味着如果用户选择 2 个复选框,我需要更新数据库两次,创建 2 行,但使用相同的garageid.

我之前尝试过发布一个关于这个的问题,但我的解释很糟糕,所以我再次尝试,希望这次我包括了所有内容。我愿意接受任何可以帮助我解决这个问题的帮助/解决方案。

标签: javascripthtmlsqlasp.net

解决方案


首先,您需要删除所有GarageCrossRequestType包含当前GarageID的复选框,因为复选框可能是checked以及unhacked稍后编辑。

我会这样做。

注意:请务必阅读评论

javascript

$("#EditGarageBtn").click(function() {
  var customerNumber = customerNumberOfEditingGarage;
  // I assumed that you want name as the int of RequestType eg 1 or 2 that are checked
  var garageCrossRequestType = $(".checkbclass:checked").map(function(x) {
   return   parseInt($(x).attr("name"));
   });
  name = $("#GarageName").val();
  countryId = $("#Country").val();
  var garageId = $("#garageId").val();
  var contactperson = $("#ContactPerson").val();
  var email = $("#Email").val();
  $("#EditGarageBtn").hide();

  if (name.length > 0 && email.length > 0 && contactperson.length > 0) {
    $.ajax({
      url: '@Url.Action("EditGarage", "Garage")',
      dataType: 'JSON',
      data: {
        name: name,
        countryId: countryId,
        garageId: garageId,
        contactperson: contactperson,
        email: email,
        garageCrossRequestType: garageCrossRequestType // here send the checked checkedboxes
      },
      success: function(data) {
        if (data == "Failure") {
          toastr["error"]("Error editing Garage");
        } else {
          toastr["success"]("Garage successfully updated");
          customerNumberOfEditingGarage = null;
          refreshGrid();
        }
      },
      error: function() {

      }
    });
  } else {
    toastr["error"]("Error editing Garage");
  }
});

C#

// create an sqlProcedure or something instead of this, this is only to show how it work
// You have to clear all GarageCrossRequestType that containe the current GarageID
// An after insert the newly checked items
new SqlCommand("delete GarageCrossRequestType where GarageID = " + model.GarageId, Connection).ExecuteNonQuery();
List <int> newlist = new List<int>();
if (model.garageCrossRequestType != null)
    newlist.AddRange(model.garageCrossRequestType);
  foreach(var item in newlist) {
    //newlist cant be null becouse you are already in a loop. 
    // and also newlist is never null
    // if (newlist != null)

    var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
    cmd1.CommandType = CommandType.StoredProcedure;
    cmd1.Parameters.AddWithValue("@GarageId", model.GarageId);
    // instead of newlist.First() you are looping throw newlist eg checkboxes then it should be item
    cmd1.Parameters.AddWithValue("@RequestType", item);

    int result = cmd1.ExecuteNonQuery();
    if (result == 1)
      valid = true;

  }

推荐阅读