Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Разработка под ASP.NET > UpdatePanel + JavaScript


Автор: Artemon 12.11.2008, 21:55
Как из JavaScript вызвать серверный PostBack, да так, чтобы не обновлять всю страницу?

Автор: Idsa 13.11.2008, 06:03
Нужно вызвать __doPostBack с указанием UniqueId UpdatePanel'и: http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript/

Автор: Artemon 13.11.2008, 15:12
Да, действительно - помогло.

Но появилась новая проблема, UpdatePanel стал обновляться, а сним также начали и другие UpdatePanels обновляться, можноли сделать обновление только для одной указанной панели?

Автор: Idsa 13.11.2008, 15:27
Для тех панелей, которые не должны обновляться при каждом постбэке, выставьте UpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional.

Автор: Idsa 14.11.2008, 03:17
Еще один нюанс насчет первого вопроса. Вызов __doPostBack('ControlUnqueId', '') лучше прописывать не ручками, а через
Код

Page.ClientScript.GetPostBackEventReference(myUpdatePanel, null);

Метод GetPostBackEventReference не только вернет строку __doPostBack('ContorlUniqueId', ''), ликвидировав возможность опечатки, но еще и зарегистрирует на странице метод __doPostBack, если этого еще не сделал другой контрол. Конечно, маловероятно, что на странице не найдется контрола, который не сделает этого... тем не менее в обратном случае без вызова GetPostBackEventReference вызовы __doPostBack перестанут работать.
P. S. Сейчас проверил.
1. Создаю пустую страницу. Запускаю - __doPostBack нет.
2. Добавляю на страницу ScriptManager. Запускаю - __doPostBack есть.
Так что ScriptManger заботится о регистрации __doPostBack, поэтому вызов GetPostBackEventReference в данном случае не даст ничего, кроме отсутствия необходимости набирать __doPostBack вручную. Тем не менее, в более общем случае стоит иметь GetPostBackEventReference в виду.

Автор: Artemon 14.11.2008, 15:44
Сделал как вы сказали, панель не обновляется визуально, НО PanelLoad всеравно вызвается, так и должно быть ?

Автор: Idsa 14.11.2008, 15:58
Artemon, должно быть так, как написано в MSDN:
Цитата

When an UpdatePanel control is not inside another UpdatePanel control, the panel is updated according to the settings of the UpdateMode and ChildrenAsTriggers properties, together with the collection of triggers. When an UpdatePanel control is inside another UpdatePanel control, the child panel is automatically updated when the parent panel is updated. 

The content of an UpdatePanel control is updated in the following circumstances: 

If the UpdateMode property is set to Always, the UpdatePanel control's content is updated on every postback that originates from anywhere on the page. This includes asynchronous postbacks from controls that are inside other UpdatePanel controls and postbacks from controls that are not inside UpdatePanel controls. 

If the UpdatePanel control is nested inside another UpdatePanel control and the parent update panel is updated. 

If the UpdateMode property is set to Conditional, and one of the following conditions occurs: 

You call the Update method of the UpdatePanel control explicitly. 

The postback is caused by a control that is defined as a trigger by using the Triggers property of the UpdatePanel control. In this scenario, the control explicitly triggers an update of the panel content. The control can be either inside or outside the UpdatePanel control that defines the trigger. 

The ChildrenAsTriggers property is set to true and a child control of the UpdatePanel control causes a postback. A child control of a nested UpdatePanel control does not cause an update to the outer UpdatePanel control unless it is explicitly defined as a trigger. 


Если контрол, который вызывает обновление, находится вне UpdatePanel'и с UpdateMode.Conditional, нужно либо добавить Trigger, либо вызывать UpdatePanel.Update вручную.

Автор: Artemon 14.11.2008, 19:29
Вопрос в другом, визуального обновления панели не происходит, если UpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional.

Но с чего вдруг срабатывает событие, которое обычно вызывется при обновлении панели (LoadPanel)?

Казалосьбы если нет обновления, тои не должно вызываться событие PanelLoad

Автор: Idsa 14.11.2008, 21:34
Цитата(Artemon @  14.11.2008,  23:29 Найти цитируемый пост)
Казалосьбы если нет обновления, тои не должно вызываться событие PanelLoad 

Ах вот Вы о чем... 
То о чем, Вы говорите, - полный жизненный цикл страницы при обновлении через UpdatePanel - и есть самый большой недостаток UpdatePanel. Тут нужно выбрать между излишней нагрузкой на сервер (из-за полного жизненного цикла) и удобством использования (кинул панельку - и забыл про какой-либо геморой).

Автор: Artemon 17.11.2008, 17:19
+1

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)