demoshop

NEWS

demo, trying to be the best.

站內搜尋載入中...

ASP.NET MVC的CheckBox應用,一堆字串中擷取GUID

  • 5139
  • 1

demo今天遇到一件事情,類似一個清單頁面讓使用者勾選需要變更的項目然後丟到後端去做應該做的事情,這種看似簡單的事情也會有問題倒是很詭異,下了中斷點,看了原始碼才發現原來ASP.NET MVC丟給我的值的並不是我想的那麼平凡,Google了一下也有人有這問題,所以就紀錄一下我的解法吧。

    先來做個測試頁面,因為demo在後端的資料庫是用GUID來當PK所以很明顯的我要知道他點了啥就是把GUID帶進去就對啦,為了測試方便,我就New五個出來假裝是資料庫撈出來的。

    <%using (Html.BeginForm()){%>
    <%=Html.CheckBox("demo",new{value=Guid.NewGuid()}) %>
    <%=Html.CheckBox("demo",new{value=Guid.NewGuid()}) %>
    <%=Html.CheckBox("demo",new{value=Guid.NewGuid()}) %>
    <%=Html.CheckBox("demo",new{value=Guid.NewGuid()}) %>
    <%=Html.CheckBox("demo",new{value=Guid.NewGuid()}) %>
    <input type="submit" value="我按" />
    <%} %> 

     Controller也很自然的這樣接它

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(FormCollection collection)
    {
    return View();
    } 

     


    接者我回到頁面隨便點兩個按下submit下中斷點看到他竟然丟給我這玩意

    false,ce3737b0-5f3c-4770-bcd0-ed15d9f1b281,false,false,94289e72-5ad6-491b-9418-e9795ca43873,false,false 

    看起來很正確沒錯,我選了兩個,所以有兩個是丟Guid給我,其他是丟false,嗯很正確,但是這樣的字串很難用阿...,所以我們就必須要處理一下,為了讓迴圈跑得方便我還是希望是丟一個以,分隔的字串給我所以我幹了這種事情。

      [AcceptVerbs(HttpVerbs.Post)]
      public ActionResult Index(FormCollection collection)
      {
          string[] stringSplit = collection.GetValue("demo").AttemptedValue.Split(',');
          string stringarray = "";
          foreach (var item in stringSplit)
          {
              try
              {
                  new Guid(item);
                  stringarray += item + ",";
              }
              catch
              {
       
              }
          }
          ViewData["GUID"] = stringarray;
          return View();
      } 

    看似很不錯,功能有了!需求也達到了!但是你有沒有覺得他滿醜的...而且用try來這樣搞好像也不太符合經濟效益,我們再來回頭看一下,ASP.NET MVC很好心的幫我們丟出來的字串的格式是怎樣?嗯看樣子屬於GUID格式的就是我們要得,那太好了這時候Regex又出現了,這種東西就是他的長項,因此我們再度請出Regex,我們的Code就變成這樣啦。

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index(FormCollection collection)
    {
        List<string> list = new List<string>();
        string Pattern ="[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}";
        foreach (var item in System.Text.RegularExpressions.Regex.Matches(collection.GetValue("demo").AttemptedValue, Pattern))
        {
            list.Add(item.ToString());
        }
        string stringarray = string.Join(",", list.ToArray());
        ViewData["GUID"] = stringarray;
     
        return View();
    } 

    看到了吧,這才叫做程式阿...其中還有一個比較特別的是demo改使用string.Join()來組合字串,這樣組出來的有一個很直接的好處,就是最後不會多一個","免去了再多一條程式來過濾,相當的不錯,如果你也有類似的需求,可以試試看demo的作法唷。