I've have a formview that is designed to update it's datasource each time a text_changed event or dropdown list has been changed. On every text_changed event and equivalent for other controls I call the formView.UpdateItem method and this causes the form to lose focus from the control I have tabbed down to.
I've tried to implement this method but I get unknown runtime errors after I have tried to select a control for the second time.
I can't help but think there is another way of dealing with this.
How would you go about solving this issue?
For things like this, I often stash the value in an asp:Hidden control (input type="hidden") using the javascript and then add a pageLoad function (in the javascript) to parse that field and then set the focus. This way the id of the focused control is persisted through the postback.
Something like this (pseudocode):
<input type="hidden" id="focusHolder" />
function onSubmit (registered via ClientScript.RegisterOnSubmitStatemnet) {
grab the target and stash id in #focusHolder
}
function pageLoad() {
$get($get('focusHolder').value).focus();
}
You can do it on server side too. Here is an example of how to put focus on the control that caused the asynchronous postback:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
string IDPostbackCtrl = GetAsyncPostBackControlID(Page, Page.Request);
ScriptManager.GetCurrent(Page).SetFocus(IDPostbackCtrl);
}
}
}
public string GetAsyncPostBackControlID(Page page, HttpRequest request)
{
string smUniqueId = ScriptManager.GetCurrent(page).UniqueID;
string smFieldValue = request.Form[smUniqueId];
if (!String.IsNullOrEmpty(smFieldValue) && smFieldValue.Contains('|'))
return smFieldValue.Split('|')[1];
return String.Empty;
}
来源:https://stackoverflow.com/questions/853390/maintaining-focus-on-ajax-update-panel-after-updating-form