【问题标题】:Show checkboxes that are already checked by getting the information from database通过从数据库中获取信息来显示已经选中的复选框
【发布时间】:2021-10-19 07:57:41
【问题描述】:

我在我的 asp 项目中创建了一个方法,我可以在其中选择一个车库并填写一些我希望与车库相关联的复选框。这些存储在数据库交叉表中。这是表结构:

SELECT [ID]
      ,[GarageID]
      ,[RequestProperty]
      ,[Active]
      ,[CreatedDate]
      ,[CreatedBy]
      ,[UpdatedDate]
      ,[UpdatedBy]
  FROM [dbo].[GarageCrossRequestType]

复选框发送后的示例数据:

ID  GarageID    RequestProperty Active  
299  64043       1                  1   
现在,我希望通过从数据库中获取信息来交叉/检查这些复选框,例如,当使用@ 987654323选择车库@ requestproperty的框,应检查/越过值1。我创建了一个用于从数据库中获取信息的 c# 方法,如下所示:
public List<GarageModel> getRequestType(int garageId)
        {
            var rModel = new List<GarageModel>();
            try
            {
                string sql = "SELECT GarageID, RequestProperty FROM¨
                GarageCrossRequestType WHERE GarageID = " + garageId;
                var cmd = new SqlCommand(sql, Connection);

                var dt = new DataTable();
                dt.Load(cmd.ExecuteReader());

                foreach (DataRow i in dt.Rows)
                {
                    var model = new GarageModel();
                    model.GarageId = Convert.ToInt32(i["GarageID"].ToString());
                    model.Values = Convert.ToInt32(i["RequestProperty"].ToString());

                    rModel.Add(model);
                }
            }
            catch(Exception ex)
            {
                var error = ex.ToString();
            }

            finally
            {
                Connection.Close();
            }

            return rModel; 
        }

调试时,这可以正常工作,并且我得到了正确的值。但是,我不知道应该如何继续填写复选框?我将分享我如何将值发送到数据库以及如何填写下面的复选框的代码。这是c#方法:

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("@Email", model.Email);
            cmd.Parameters.AddWithValue("@Note", model.Note);
            try
            {

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

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

            }
            finally
            {
                Connection.Close();
            }

            // Add request types for garage when editing garage
            if (model.garageCrossRequestType != null) { 
            foreach (var item in model.garageCrossRequestType)
            { 
               var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
               cmd1.CommandType = CommandType.StoredProcedure;
               cmd1.Parameters.AddWithValue("@GarageId", model.GarageId);
               cmd1.Parameters.AddWithValue("@RequestType", item);
               cmd1.Parameters.AddWithValue("@Active", 1);

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

            }
            }

            return valid;
        }

HTML(索引):

  @foreach (var items in Model)
            {
                <style>
                    .ab{
                        margin-right: 8px;
                    }
                </style>

                <div style=" width: 40%; display: block; float: right; margin-right: 10%; margin-top: 10%;">
                    <h4>Choose request types for garage:</h4><br />
                    <div class='form-group'>
                        <div class="rowa">
                            <label class="ab">Claim</label>
                            <input type="checkbox" class="checkbclass" name="@items.Claim" id="@items.Claim" placeholder="Tires" value="1" /> <!-- values for request type -->
                        </div>
                    </div>
                    <div class='form-group'>
                        <div class="rowa">
                            <label class="ab">Scheduled Service</label>
                            <input type="checkbox" class="checkbclass" name="@items.ScheduledService" id="@items.ScheduledService" placeholder="Scheduled" value="2" />
                        </div>
                    </div>
                    <div class='form-group'>
                        <div class="rowa">
                            <label class="ab">Tires</label>
                            <input type="checkbox" class="checkbclass" name="@items.Tires" id="@items.Tires" placeholder="Tires" value="3" />
                        </div>
                    </div>
                    <div class='form-group'>
                        <div class="rowa">
                            <label class="ab">Rent Replacement Car</label>
                            <input type="checkbox" class="checkbclass" name="@items.RentRepalcementCar" id="@items.RentRepalcementCar" placeholder="Tires" value="4" />
                        </div>
                    </div>
                    <div class='form-group'>
                        <div class="rowa">
                            <label class="ab">Other Work</label>
                            <input type="checkbox" class="checkbclass" name="@items.OtherWork" id="@items.OtherWork" placeholder="Tires" value="5" />
                        </div>
                    </div>
                    <div class='form-group'>
                        <div class="rowa">
                            <label class="ab">Insurance</label>
                            <input type="checkbox" class="checkbclass" name="@items.Insurance" id="@items.Insurance" placeholder="Tires" value="6" />
                        </div>
                    </div><br />
                </div>
            }

JavaScript/Jquery:

$("#EditGarageBtn").click(function () {
            var customerNumber = customerNumberOfEditingGarage;
            name = $("#GarageName").val();
            countryId = $("#Country").val();
            var garageId = $("#garageId").val();
            var note = $("#Note").val();
            var email = $("#Email").val();

            var garageCrossRequestType  = $(".checkbclass:checked").map(function () {
                return $(this).val(); // to see which request types are checked
            }).toArray();
            console.log(garageCrossRequestType);

            $("#EditGarageBtn").hide();

            if (countryId == "Norway")
                countryId = 2;
            if (countryId == "Finland")
                countryId = 4;

            if (name.length > 0 && email.length > 0 && phone.length > 0 && contactperson.length > 0) {
            $.ajax({
                url: '@Url.Action("EditGarage", "Garage")',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    garageCrossRequestType: garageCrossRequestType,
                    name: name, countryId: countryId, garageId: garageId, 
                    note: note, 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");
            }
        });

现在,我尝试执行类似于上面代码的 ajax 调用,以便在使用 console.log 时至少从数据库中获取数据,但我似乎也无法将数据从控制器获取到索引.所以我想我需要帮助的是 1.如何获取在我的 c# 方法中获得的数据以显示在视图中和 2.如何连接它以便使用值检查正确的复选框?或者也许我已经完全离开了,还有更简单的方法可以做到这一点?

感谢您的帮助!

更新:所以我创建添加了这个 Ajax 调用:

 $.ajax({
                    type: "POST",
                    url: '@Url.Action("getRequestType", "Garage")?garageId=' + garageId,
                      dataType: 'JSON',
                      data: {
                          garageId: garageId, Values: Values
                      },
                        sucess: function (data) {
                            if (data != "Failure") {
                                //return garageId, value;
                        }
                    }
                  }); console.log(garageId, Values);

它可以工作等等,我可以在控制台日志中看到我可以获得 garageIdValue。但是(大声笑)现在的问题是我可以像这样在模型中进行测试:

public int Values { get; set; } = 5;

当我使用控制台日志时,这将导致显示数字 5 和正确的 garageid。但是getRequestType 方法中的值似乎没有连接到模型。正如所见,我在方法中使用了foreach loop,并将model.Values 设置为来自RequestProperty 的数据库值。所以如果我将模型设置为:

public int? Values { get; set; } = null;

例如,它将显示空等。所以有些东西显然不能正常工作。但是,我似乎无法弄清楚该方法有什么问题,因此再次非常感谢您的帮助! (经典编程解决了一个问题,却发现了另一个问题,哈哈)

【问题讨论】:

    标签: javascript c# jquery sql asp.net


    【解决方案1】:

    嗯,我认为 listView 效果更好。

    对于选择列表,请使用复选框列表。

    所以我们有

    tblGarage       - our list of garages
    tblitemsInGarge - list of times in each garage
    tblItems        - our list of possible choices.
    

    所以,说这个标记:

        <asp:ListView ID="LvGarage" runat="server" DataKeyNames="ID" OnItemDataBound="LvGarage_ItemDataBound" >
            <ItemTemplate>
                <tr style="">
                    <td><asp:Label ID="GarageNameLabel" runat="server" Text='<%# Eval("GarageName") %>' /></td>
                    <td><asp:Label ID="GarageTypeLabel" runat="server" Text='<%# Eval("GarageType") %>' /></td>
                </tr>
                 <tr>
                    <td colspan="2">
                    <h4>Items in Garage</h4>
                     <asp:CheckBoxList ID="ckList" runat="server"
                        CellPadding="10" CellSpacing="20" 
                        DataTextField="ItemName" DataValueField="ID" 
                        RepeatDirection="Horizontal"></asp:CheckBoxList>
                        <hr style="border:solid;border-top:1px"/>
                    </td>
                  </tr>
            </ItemTemplate>
            <LayoutTemplate>
                <table id="itemPlaceholderContainer" runat="server" border="0" Class="table table-hover">
                    <tr runat="server" style="">
                        <th runat="server">GarageName</th>
                        <th runat="server">GarageType</th>
                    </tr>
                    <tr id="itemPlaceholder" runat="server">
                    </tr>
                </table>
            </LayoutTemplate>
        </asp:ListView>
        <br />
    
         <asp:Button ID="cmdSave" runat="server" Text="Save Changes" CssClass="btn-default" OnClick="cmdSave_Click" />
    

    我们现在加载 ListView,但是对于每一行,我们从数据库中提取选择。 (行数据绑定)。

    所以,我们要加载的代码是这样的:

        DataTable rstItems = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadMyView();
        }
    
        public void LoadMyView()
        {
            rstItems = MyRst("SELECT ID, ItemName from tblItems ORDER BY ItemName");
    
            LvGarage.DataSource = MyRst("SELECT * From tblGarage ORDER BY GarageName");
            LvGarage.DataBind();
        }
    
        public DataTable MyRst(string strSQL)
        {
            var rst = new DataTable();
            using (SqlCommand cmdSQL = new SqlCommand(strSQL,
                new SqlConnection(Properties.Settings.Default.TEST4)))
            {
                cmdSQL.Connection.Open();
                // fill items table
                rst.Load(cmdSQL.ExecuteReader());
            }
            return rst;
        }
    

    但是,我们需要在 Row 数据绑定上填写复选框列表(选择表),并且还设置选中的那些(来自 tbleItemsInGarage)。

    我们有这个:

        protected void LvGarage_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                CheckBoxList ckList = (CheckBoxList)e.Item.FindControl("ckList");
    
                ckList.DataSource = rstItems;
                ckList.DataBind();
    
                // now get all rows for this garage
                int ID = (int)LvGarage.DataKeys[e.Item.DataItemIndex]["ID"];
                DataTable rstItemsChecked = new DataTable();
                rstItemsChecked = MyRst("SELECT * FROM tblItemsInGarage WHERE Garage_ID = " + ID);
                foreach (DataRow OneRow in rstItemsChecked.Rows)
                    ckList.Items.FindByValue(OneRow["Item_ID"].ToString()).Selected = true;
            }
        }
    

    现在的输出是这样的:

    我们现在只需要一个保存按钮即可将您所做的任何更改发送回数据库。该代码如下所示:

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lvRow in LvGarage.Items)
            {
                // now get all rows for this garage
                int ID = (int)LvGarage.DataKeys[lvRow.DataItemIndex]["ID"];
                string strSQL = "SELECT ID, Item_ID, Garage_ID FROM tblItemsInGarage WHERE Garage_ID = " + ID;
    
                using (SqlCommand cmdSQL = new SqlCommand(strSQL,
                    new SqlConnection(Properties.Settings.Default.TEST4)))
                {
                    cmdSQL.Connection.Open();
                    SqlDataAdapter dUpdate = new SqlDataAdapter(cmdSQL);
                    SqlCommandBuilder sUpdate = new SqlCommandBuilder(dUpdate);
                    DataTable rstItemsChecked = new DataTable();
                    rstItemsChecked.Load(cmdSQL.ExecuteReader());
    
                    // remove all selected
                    foreach (DataRow OneRow in rstItemsChecked.Rows)
                        OneRow.Delete();
    
                    // now add back ONLY checked items
                    CheckBoxList ckList = (CheckBoxList)lvRow.FindControl("ckList");
                    foreach (ListItem citem in ckList.Items)
                    {
                        if (citem.Selected)
                        {
                            DataRow OneRow = rstItemsChecked.NewRow();
                            OneRow["Item_ID"] = citem.Value;
                            OneRow["Garage_ID"] = ID;
                            rstItemsChecked.Rows.Add(OneRow);
                        }
                    }
                    dUpdate.Update(rstItemsChecked);
                }
            }
        }
    

    现在有点代码,但不要太多!!!

    使用列表视图,放入该复选框列表并从选择表中驱动复选框列表。

    我们得到:

    not a lot of markup
    not a lot of code to load
    But REALLY make gains in the database update process.
    

    总而言之,代码不多,因为我们必须从该复选框列表中拉+推回选择。

    【讨论】:

    • 哇,谢谢!我正在尝试代码,我唯一的问题是我收到一个错误,因为“当前上下文中不存在名称'LvGarage'”,但我试图找出原因!这段代码很棒,我以前从未使用过 ListViews,所以谢谢
    • 嗯,LvGarage这个名字不存在错误不想消失,知道为什么会这样吗?
    • LvGarage 在我的代码中只是网格视图控件的名称(id)。不知道这会对这个问题产生什么影响——你当然可以为任何控件命名你想要的任何东西——但 lvGarage 只是我在这里使用的 Grid View 控件的 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多