2016年1月6日 星期三

[MVC]CheckBox複選、全選、取消

我忘了有沒有寫過類似的東西 剛好今天有空,索性整理一下吧
JQUERY
  1. // Tab名稱的全選和取消
  2. $("#AllTab").change(function () {
  3. if ($(this).is(":checked")) {
  4. $("[id*=chkTab] input").prop("checked", true);
  5. } else {
  6. $("[id*=chkTab] input").removeAttr("checked");
  7. }
  8. });
  9. $("[id*=chkTab] input").on("change", function () {
  10.  
  11. //全部都選到了,"全部"這個選項打勾,反之,則取消
  12. if ($("[id*=chkTab] input").length == $("[id*=chkTab] input:checked").length) {
  13. $("#AllTab").prop("checked", true);
  14. }
  15. else {
  16. $("#AllTab").removeAttr("checked");
  17. }
  18. });
View 順便講一下好了,checkList 這個是用來記錄CheckBox選取的狀態 MVC 才可以這樣用......
  1. //這段程式碼可以不用理他,是POSTBACK 回來時
  2. //想讓畫面保留勾選的項目
  3. @{
  4. string[] checkList = new string[7];//最後一個存放 全部 的狀態
  5. if (splitFilter[1] != null)
  6. {
  7. string[] splitck = splitFilter[1].TrimEnd(',').Split(',');
  8. if (splitck[0] != "-1")
  9. {
  10. foreach (string i in splitck)
  11. {
  12. checkList[int.Parse(i) - 1] = "checked";
  13. }
  14. }
  15. }
  16. }

Checkbox是長這樣的

<input type="checkbox" value="1" @checkList[1]><label>AA</label>




 Controller

接到勾選的Tab後,去DB搜尋
之前寫的不太簡潔,順帶記錄一下新寫法

  1. if (Tag != "-1")
  2. {
  3. List TagCondition = new List();
  4. foreach (var t in Tag.Substring(0, Tag.Length - 1).Split(','))
  5. {
  6. TagCondition.Add(Convert.ToInt32(t));
  7. }
  8. product = product.Where(x =>TagCondition.Contains(x.TabName));
  9. }

沒有留言:

張貼留言