2013-03-08 88 views
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)来做到这一点,但我对如何构建这一点毫无头绪。 我需要返回一个项目列表。那么我怎么能做到这一点?非常感谢你!

+0

只需提供该模型的ID为您的复选框的值,然后接受一个'IList的'(或'Int32',' Guid'等)并交叉引用已选择和提交的内容。 (另外,有趣的是你有以'm_ *'开头的公共属性,因为这通常是类成员(内部)的象征_) – 2013-03-08 20:56:57

+0

你是否问如何在POST中将它发回给你的控制器呢? – 2013-03-08 20:59:15

+0

@MikeC。 :是的,确切地说。 – hsim 2013-03-08 21:00:16

回答

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

在这里,我只是随机选择为您的行动,但你需要使它与您在任何操作(编辑,索引,等等。)

祝您好运!

+0

谢谢,将在此工作,并会回复你。至于愚蠢的名字,它只为了这个问题,不要担心:) – hsim 2013-03-08 21:04:14

+0

作品!非常感谢你,今天你一直很棒! – hsim 2013-03-08 21:10:36

0

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

$(document).ready(function() { 
     $("#selectAll").click(function() { 
      var chkValue = $(this).is(":checked"); 
      $(".divChckBox").attr("checked", chkValue); 
     }); 
    }); 
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(); 
    } 
    /* ... */ 
} 
相关问题