在asp.net mvc 下 checkbox的值怎麼獲取?
微軟的MVC框架出了有一段時間了,最近在用它做個東西,使用過程中發現了一個小問題就是Html.CheckBox方法生成的Checkbox的值在服務器端獲取出現異常,於是仔細研究了一下它的源代碼,找到了原因。
我本以爲可以有個bool.TryPrase方法進行轉換,但是不行,永遠返回false值,於是查看了一下源代碼,發現Html.CheckBox方法生成的html代碼裏面不僅有一個input type=checkbox,還有一個input type=hidden,而且2個的name屬性是一樣的,這樣的話提交到服務器上會是一個已,號連接的字符串,bool.TryPrase方法肯定返回false了,但是爲什麼這樣呢?
於是下載了mvc的源代碼,發現瞭如下的註釋:
Render an additional <input type="hidden".../>
for checkboxes. This addresses scenarios where unchecked checkboxes are not sent in
the request. Sending a hidden input makes it possible to know that the checkbox was present on the page when the request was submitted.
原來是這樣,如果checkbox不選的話是不會有數據提交到服務器端的,所以程序自動加了一個hidden,這樣無論checkbox選擇沒選擇,都會有數據提交到服務器端,,可能是爲了方便程序處理把。
那麼這樣的話
如果checkbox被選中,則服務器收到的true,false。
checkbox未選中,因爲有hidden的input存在所以服務器則收到flase。
那麼,我們用如下代碼即可獲得checkbox的選中狀態
-
Request.forms[Key].Contains("true");