使用ASP .Net 2.0發現一個很大問題是在Javascript無法直接使用getElementById。在ASP頁面中的ID無法直接引用。
ASP.NET 2.0 name mangling
1:需要使用
var CtrlCust=document.getElementById(<%Ctrl.ClientID%>);
2:但是如果控制項是在FormView GridView DetailView就不行了,需要使用FindControl
txBox=(TextBox)DataSourceItemView.FindControl("TextBox");
先找到這個控制項。然後txBox.ClientID, 並且Javascript需要在Page_Load中載入
3:但是這裡還有問題,方法2中只是適合Default View,如果View有了變化,例如原來是Readonly轉換到EditTemplate的時候,EditTemplate裡面的控制項使用ItemView.Find無法找到。所以需要另外的方法。在Item_Created中載入Javascript
我這裡實現的是快顯視窗,返回一個數值
protected void FormView1_ItemCreated(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
TextBox CustTextBox = (TextBox)FormView1.FindControl("main_customerTextBox");
if (CustTextBox == null) return;
string js = "<script language='javascript'>";
js = js + "function findcust(CustButton)";
js = js + "{";
js = js + " var ttop = CustButton.offsetTop; ";
js = js + " var thei = CustButton.clientHeight;";
js = js + " var tleft = CustButton.offsetLeft;";
js = js + " while (CustButton = CustButton.offsetParent){ttop+=CustButton.offsetTop; tleft+=CustButton.offsetLeft;}";
js = js + " var returnValue=window.showModalDialog('../Common/CommonFindCustomer.aspx','Pass paramerter to Child Window','dialogWidth:600px;dialogHeight:500px;dialogLeft:'+tleft+';dialogTop:'+ttop+';resizable:yes ');";
js = js + " if (returnValue == null) return;";
js = js + " var CtrlCust=document.getElementById('" + CustTextBox.ClientID + "');";
js = js + " if (CtrlCust==null)";
js = js + " alert('Not Found Customer Control');";
js = js + " else";
js = js + " CtrlCust.value=returnValue;";
js = js + "}</script>";
ClientScript.RegisterStartupScript(this.GetType(),"FindCustScript", js);
}
請參考以下
How to access control in FormView
http://www.dotnettaxi.com/ViewTopic137362.aspx
FormView - FindControl only works for default view
http://www.dotnettaxi.com/ViewTopic138828.aspx
http://west-wind.com/weblog/posts/5127.aspx