当用户点击文本框时,我必须执行服务器端事件。到目前为止,我可以管理使用onfocus事件调用javascript函数,但如果我尝试删除onfocus,执行一些代码,将焦点重新放回控件,然后在无限循环中再次重新触发onfocus事件。以下示例......
HTML
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" onfocus="CallServer(this);"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" onfocus="CallServer(this);"></asp:TextBox>
的Javascript
function CallServer(obj) {
if (obj != "") {
var control = document.getElementById(obj.id)
__doPostBack(obj.id, "onfocus");
}
}
代码隐藏
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim target As String = Page.Request.Params.Get("__EVENTTARGET")
Dim eventarg As String = Page.Request.Params.Get("__EVENTARGUMENT")
Dim PostControl As Control = Nothing
If target <> "" Then
PostControl = Page.FindControl(target)
End If
If eventarg = "onfocus" Then
CType(PostControl, TextBox).Attributes("onfocus") = "null"
...do some code
Page.SetFocus(PostControl)
CType(ctrl, TextBox).Attributes.Add("onfocus", "CallServer(this)")
End If
End If
End Sub
答案 0 :(得分:0)
您可以使用Page_PreRender中的ScriptManager.SetFocus来完成此操作。在这种情况下,ScriptManager位于MasterPage。
Private Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
If HiddenFieldPostBackControl.Value <> "" Then
Dim PostBackControl As Control = FindControlById(HiddenFieldPostBackControl.Value)
If PostBackControl IsNot Nothing Then
Dim sm As ScriptManager = ScriptManager.GetCurrent(Master.Page)
sm.SetFocus(PostBackControl )
End If
End If
End Sub
注意:如果您正在使用动态控件(必须在每次回发时重新创建),则必须在将事件添加到其他控件时删除目标控件的(OnFocus of OnFocusIn)事件。这必须在Page_PreRender之前完成。
function ControlOnFocus(ctrl, request, doc, min, max, docSec) {
if (ctrl != "") {
var hf = document.getElementById("MainContent_HiddenFieldPostControl").value = ctrl.id;
var c = document.getElementById(ctrl.id);
PostControl = ctrl;
//ONFOCUS
if (request.toLowerCase() == 'server') {
//SERVER Handler
__doPostBack(ctrl.id, "onfocus");
} else {
//CLIENT Handler
//Your code here...
}
ReAssignEvent(ctrl.id);
var hf = document.getElementById("MainContent_hfValidated");
hf.innerText = "";
};
};
function ReAssignEvent(ControlID) {
//loop through an array with (id,onfocus event) for each control
//this array is only required for the focus event
for (var i = 0; i < FocusArray.length; i++) {
var carr = FocusArray[i].split("[1]"); //split the element to get id and event
var carrId = carr[0]; //get the id
var c = document.getElementById(carrId); //find control and assign control to var
var e = carr[1]; //assing event as string to var
if (c != null) {
if (ControlID!= carrId) {
if (c.type == "text" || c.type == "select-one") {
c.setAttribute("onfocus", e);
} else {
c.setAttribute("onfocusin", e);
}
} else {
if (c.type == "text" || c.type == "select-one") {
c.removeAttribute("onfocus");
} else {
c.removeAttribute("onfocusin");
}
}
}
}
}