0

我正在构建一个 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)来做到这一点,但我对如何构建它一无所知。我需要返回一个项目列表。那么我该怎么做呢?非常感谢你!

4

3 回答 3

0

尝试使用该attr方法更改属性checked

$(document).ready(function() {
        $("#selectAll").click(function() {
            var chkValue = $(this).is(":checked");
            $(".divChckBox").attr("checked", chkValue);
        });
    });
于 2013-03-08T20:57:41.633 回答
0

您的表单将根据名称返回值,因此请射杀告诉您如此愚蠢名称的人 :)
使用

<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 属性相匹配。实际值将是您的复选框的值。

在这里,我只是为您的操作随机选择了创建,但您需要使其与您所在的任何操作(编辑、索引等)相匹配。

祝你好运!

于 2013-03-08T21:00:52.700 回答
0

查看代码:

<!-- 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();
    }
    /* ... */
}
于 2013-03-08T21:03:51.493 回答