2012年4月2日 星期一

radiobuttonlist selectedindexchanged 與 UpdatePanel Trigger

為了讓ASP.NET的RadioButtonList呈現連動選單,通常會讓RadioButtonList作PostBack
如此一來,就可以順利地產生連動選單。

但是,如果搭配上UpdatePanel的Trigger時會出現一個詭異的現象,就是在有預設值的情況下,會發生無法正常觸發非同步更新的狀況。


測試半天後,決定看原始碼來Debug比較快。
不看還好,一看就發現了好玩的事情....= =。

<span id="rbListSrvtpe2">
<input id="rbListSrvtpe2_0" type="radio" name="rbListSrvtpe2" value="14" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$0\',\'\')', 0)" /><label for="rbListSrvtpe2_0">AA</label><br />
<input id="rbListSrvtpe2_1" type="radio" name="rbListSrvtpe2" value="15" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$1\',\'\')', 0)" /><label for="rbListSrvtpe2_1">BB</label><br />
<input id="rbListSrvtpe2_2" type="radio" name="rbListSrvtpe2" value="16" checked="checked" /><label for="rbListSrvtpe2_2">CC</label><br />
<input id="rbListSrvtpe2_3" type="radio" name="rbListSrvtpe2" value="17" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$3\',\'\')', 0)" /><label for="rbListSrvtpe2_3">DD</label>
</span>

看出來了嗎?
當我的RadioButtonList有預設值後,後面會少了 onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$2\',\'\')', 0)" /> 這段,所以當使用者,重新點選預設選項後,就不會doPostBack.......= =。

因為,這段的設定是 RadioButtonList.AutoPostBack 設定 true 時,會自動幫每一個選項加上去的,目的在於點選項目後送回 Server 端處理,預設的項目沒被加上去。

當然也就不會有任何的事件發現........冏rz。

好吧~知道原因了。
就要想想怎解決了....Orz。
山不轉路轉,路不轉自己轉,那就自己有動加入好了....XDXD
很乾脆的,在RadioButtonList.PreRender的事件中加入

RadioButtonList rbList = ((RadioButtonList)sender);
foreach (ListItem item in rbList.Items)
{
//檢查如果為預設選項就補上doPostBack JS
if (item.Selected)
{
item.Attributes.Add("onclick", String.Format("javascript:setTimeout('__doPostBack(\\'{0}${1}\\',\\'\\')', 0)",
rbList.UniqueID,
rbList.Items.IndexOf(item)));
}
}

重新編譯程式,看一下網頁原始檔

<span id="rbListSrvtpe2">
<input id="rbListSrvtpe2_0" type="radio" name="rbListSrvtpe2" value="14" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$0\',\'\')', 0)" /><label for="rbListSrvtpe2_0">AA</label><br />
<input id="rbListSrvtpe2_1" type="radio" name="rbListSrvtpe2" value="15" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$1\',\'\')', 0)" /><label for="rbListSrvtpe2_1">BB</label><br />
<input id="rbListSrvtpe2_2" type="radio" name="rbListSrvtpe2" value="16" checked="checked" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$2\',\'\')', 0);" /><label for="rbListSrvtpe2_2">CC</label><br />
<input id="rbListSrvtpe2_3" type="radio" name="rbListSrvtpe2" value="17" onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$3\',\'\')', 0)" /><label for="rbListSrvtpe2_3">DD</label>
</span>



onclick="javascript:setTimeout('__doPostBack(\'rbListSrvtpe2$2\',\'\')', 0)" />順利補上了,問題也解了~:)





沒有留言:

張貼留言