<script type="text/javascript">
function GetUser(TxtEmpID, TxtEmpName, url) {
var properties = 'status:no;resizable:no;toolbar=no;menubar=no;' +
'location=no;scroll:no;dialogWidth:540px;dialogHeight:450px;';
var arg = window.showModalDialog(url, "", properties);
if (arg != null) {
document.getElementById(TxtEmpID).value = arg[0];
document.getElementById(TxtEmpName).value = arg[1];
}
}
</script>
<table width="240px" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 80px">
<asp:Label ID="Label1" runat="server" Text="選擇課級別一" Width="80px" class="font-w"></asp:Label>
</td>
<td style="width: 80px">
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="false" Width="80px" onfocus="this.blur()"></asp:TextBox>
</td>
<td style="width: 80px">
<asp:TextBox ID="TextBox2" runat="server" ReadOnly="false" Width="80px"></asp:TextBox>
</td>
<td style="width: 80px">
<asp:Button ID="Button1" runat="server" Text="確定" OnClick="Button1_Click" CssClass="ButtonCss"/>
</td>
<td><asp:Label ID="Label3" runat="server" Text=""></asp:Label></td>
<td><asp:Label ID="Label4" runat="server" Text=""></asp:Label></td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e) {
TextBox1.Attributes.Add("onclick",
"GetUser('" + this.TextBox1.ClientID + "','" +
this.TextBox2.ClientID + "','WebDialog.aspx)");
}
這一步是 ASP.NET 的關鍵:伺服器控制項的 ID 與最終輸出的 client id 可能不同(尤其被包在命名容器中時),所以必須用 ClientID 把真正的 id 傳給前端函式。
<script language="javascript" type="text/javascript">
function Submit() {
var arr = new Array();
arr[0] = document.getElementById('TxtEmpID').value;
arr[1] = document.getElementById('TxtEmpCName').value;
arr[2] = document.getElementById('TxtTitleID').value;
window.returnValue = arr; // 把陣列設為回傳值
window.close();
}
</script>
<table>
<tr><td>
<asp:TextBox ID="TxtEmpID" runat="server" Width="50px" ReadOnly="true" CssClass="InputCss"></asp:TextBox>
<asp:TextBox ID="TxtEmpCName" runat="server" Width="60px" ReadOnly="true" CssClass="InputCss"></asp:TextBox>
<asp:TextBox ID="TxtTitleID" runat="server" Width="40px" ReadOnly="true" CssClass="InputCss"></asp:TextBox>
</td></tr>
<tr><td>
<input id="Button1" type="button" value="確 定" onclick="Submit()"/>
</td></tr>
</table>
window.returnValue,再關閉視窗。arg 拿到那個陣列,依序填入兩個 TextBox。showModalDialog 只支援舊版 IE。它從未成為標準,Chrome 與 Firefox 都不實作(Chrome 曾短暫支援後移除)。跨瀏覽器專案請改用 window.open 搭配 window.opener 回寫,或自己做一個 modal 覆蓋層搭配 AJAX。
注意 TextBox1 上的 onfocus="this.blur()"。這是為了讓唯讀欄位不要取得焦點,屬於體驗上的小細節。
Dialog 中的 TextBox 同樣要用 ClientID。範例直接寫 getElementById('TxtEmpID') 是因為該頁沒有命名容器;若控制項被包在 Master Page 或 UpdatePanel 裡,一樣得改用 ClientID。