2013-03-08 85 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(); 
    } 
    /* ... */ 
} 
相關問題