2016年1月6日 星期三

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

我忘了有沒有寫過類似的東西 剛好今天有空,索性整理一下吧
JQUERY
         // Tab名稱的全選和取消
         $("#AllTab").change(function () {
             if ($(this).is(":checked")) {
                 $("[id*=chkTab] input").prop("checked", true);
             } else {
                 $("[id*=chkTab] input").removeAttr("checked");
             }
         });
         $("[id*=chkTab] input").on("change", function () {

             //全部都選到了,"全部"這個選項打勾,反之,則取消
             if ($("[id*=chkTab] input").length == $("[id*=chkTab] input:checked").length) {
                 $("#AllTab").prop("checked", true);
             }
             else {
                 $("#AllTab").removeAttr("checked");
             }
         });
View 順便講一下好了,checkList 這個是用來記錄CheckBox選取的狀態 MVC 才可以這樣用......
//這段程式碼可以不用理他,是POSTBACK 回來時
//想讓畫面保留勾選的項目
@{ 
    string[] checkList = new string[7];//最後一個存放 全部 的狀態
    if (splitFilter[1] != null)
    {
      string[] splitck = splitFilter[1].TrimEnd(',').Split(',');
      if (splitck[0] != "-1")
      {
         foreach (string i in splitck)
         {
           checkList[int.Parse(i) - 1] = "checked";
          }
      }
                                 
    }
 }

Checkbox是長這樣的

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




 Controller

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

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

沒有留言:

張貼留言