簡體   English   中英

檢查是否在項目列表中選中了一個復選框

[英]Check if a checkbox is checked in a list of items

我正在構建一個MVC應用程序,現在我的視圖生成了一堆項目。 用戶需要檢查是否要發送數據的復選框。

這是我的觀點及其構建方式:

<script type="text/javascript">
    $(document).ready(function() {
        //alert("The document is ready");
        $("#selectAll").click(function() {
            //alert("The case has been clicked");
            var chkValue = $(this).is(":checked");
            $(".divChckBox").prop("checked", chkValue);
        });
    });
</script>
<p>
    @using (Html.BeginForm("SendObj", "Manager"))
    {
        <p>
            Select / UnSelet All Items @Html.CheckBox("selectAll", true) 
        </p>
        <table>
            <tr>
                <th>Card Name</th>
                <th>Number In Stock</th>
                (...)
            </tr>
            @for (int i = 0; i < Model.Count(); i++)
            {
                <tr>
                    <td>@Html.DisplayFor(x => x[i].m_OthObj.m_ObjName)</td>
                    <td>@Html.DisplayFor(x => x[i].m_NbInStock)@Html.HiddenFor(x => x[i].m_NbInStock)</td>
                    (...)
                    <td>
                        <input type="checkbox" name="itdoesnotmatter" class="divChckBox" checked="true"/>
                    </td>
                </tr>
            }

        </table>
        <input type="submit" value="Send"/>
    }
</p>

因此,您了解了為什么我不能使用“ CheckboxFor”。 現在,我只想發送復選框狀態為“已選中”的項目。 我知道如何通過模型綁定(checkboxfor)來做到這一點,但是對於如何構建它我一無所知。 我需要返回物品清單。 那我該怎么辦呢? 非常感謝你!

嘗試使用attr方法更改checked的屬性。

$(document).ready(function() {
        $("#selectAll").click(function() {
            var chkValue = $(this).is(":checked");
            $(".divChckBox").attr("checked", chkValue);
        });
    });

您的表單將根據名稱返回值,因此請射擊告訴您這種愚蠢名稱的人:)
采用

<input type="checkbox" name="InStock" class="divChckBox" checked="true" value="@Model[i].ID" />

或更具有代表性的東西。 請注意,提供唯一的標識符作為復選框的值很重要。 該值是您將如何識別已檢查內容的方法!

在您的控制器中,有幾種捕獲它的方法。 我這樣做是這樣的:

public ActionResult Create(List<int> InStock)
{
  foreach(var inStockItem in InStock)
  {
    //do what you need to do
  }
}

要點:

List<int> InStock

這必須與您的復選框上的NAME屬性匹配。 實際值將是您的復選框的值。

在這里,我只是隨機選擇“為您的操作創建”,但是您需要使其與您所從事的任何操作(編輯,索引等)相匹配。

祝好運!

查看代碼:

<!-- note "x[i].m_id"; Use the entity's id property is here
     ...maybe this should be m_NbInStock? -->
<input type="checkbox" name="selectedItems" value="@x[i].m_id" class="divChckBox" checked="true"/>

控制器代碼:

public class Manager : Controller
{
    /* ... */
    [HttpPost]
    public ActionResult SendObj(IList<Int32> selectedItems)
    {
      // Grab those items by their IDs found within `selectedItems` and perform
      // any processing necessary

      // ...
      //return View();
    }
    /* ... */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM