2009-11-06 3 views
1

Вот отрывок, который не работает:Страница Asp.Net с Ajax перезагружает всю страницу каждый раз, почему?

<form id="form1" runat="server"> 

    <div> 
     This is the time : 
     <br /> 
     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> 
     <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional" ChildrenAsTriggers="false"> 

      <ContentTemplate> 
       <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> 
      </ContentTemplate> 

      <Triggers> 
       <asp:AsyncPostBackTrigger ControlID="btnRefresh"/> 
      </Triggers> 

     </asp:UpdatePanel> 

     <br /> 
     <asp:Button ID="btnRefresh" runat="server" text="Refresh" OnClick="btnRefresh_Click"/> 
    </div> 

</form> 

В коде позади:

protected void Page_Load(object sender, EventArgs e) 
    { 

    Clock c = new Clock(); 
    string display = c.GetCurrentTime().ToLongTimeString(); 
    this.Title = display; 
    this.txtDate.Text = display; 

    } 

    protected void btnRefresh_Click(object sender, EventArgs e) 
    { 
    Clock c = new Clock(); 
    string display = c.GetCurrentTime().ToLongTimeString(); 
    this.txtDate.Text = display; 
    } 

Почему перезагрузки страницы, а не только UpdatePanel?

ответ

3

Хорошо я полагаю, это потому, что все были успешными, но не я, так что я думаю, что было где-то конфигурацию.

На самом деле, вам нужно иметь некоторый тег в web.config, чтобы иметь возможность использовал Framework Ajax, и я пропускал некоторые здесь теперь мой web.config:

<?xml version="1.0"?> 
<configuration> 

    <configSections> 
     <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> 
     <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> 
      <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/> 
      <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> 
      <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" /> 
      <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> 
      <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" /> 
      </sectionGroup> 
     </sectionGroup> 
     </sectionGroup> 
    </configSections> 

    <appSettings/> 
    <connectionStrings/> 

    <system.web> 

     <pages> 
     <controls> 
      <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
     </controls> 
     </pages> 

     <!-- 
      Set compilation debug="true" to insert debugging 
      symbols into the compiled page. Because this 
      affects performance, set this value to true only 
      during development. 
     --> 
     <compilation debug="true"> 
       <assemblies> 
        <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></assemblies> 
     </compilation> 
     <!-- 
      The <authentication> section enables configuration 
      of the security authentication mode used by 
      ASP.NET to identify an incoming user. 
     --> 
     <authentication mode="Windows"/> 
     <!-- 
      The <customErrors> section enables configuration 
      of what to do if/when an unhandled error occurs 
      during the execution of a request. Specifically, 
      it enables developers to configure html error pages 
      to be displayed in place of a error stack trace. 

     <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> 
      <error statusCode="403" redirect="NoAccess.htm" /> 
      <error statusCode="404" redirect="FileNotFound.htm" /> 
     </customErrors> 
     --> 

     <httpHandlers> 
     <remove verb="*" path="*.asmx"/> 
     <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
     <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
     <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> 
     </httpHandlers> 

     <httpModules> 
     <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
     </httpModules> 
    </system.web> 

     <system.web.extensions> 
     <scripting> 
      <webServices> 

      </webServices> 

     </scripting> 
     </system.web.extensions> 

     <system.webServer> 
     <validation validateIntegratedModeConfiguration="false"/> 
     <modules> 
      <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
     </modules> 
     <handlers> 
      <remove name="WebServiceHandlerFactory-Integrated" /> 
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" 
       type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" 
       type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> 
     </handlers> 
     </system.webServer> 



</configuration> 

дам + 1 всем, кто дает мне достаточно намека. Спасибо всем

0

Попробуйте установить KidsAsTriggers на True.

+0

Это не имеет значения, потому что кнопка не является дочерним элементом панели обновления, она выходит за пределы панели обновления. –

1

Я удалил «ChildrenAsTriggers», а также установил «EventName» для триггера.

Вам также может потребоваться позвонить: UpdatePanel1.Update() внутри вашей функции щелчка, так как UpdatePanel установлен как «Условный».

<form id="form1" runat="server"> 

    <div> 
     This is the time : 
     <br /> 
     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> 
     <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional"> 

      <ContentTemplate> 
       <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> 
      </ContentTemplate> 

      <Triggers> 
       <asp:AsyncPostBackTrigger ControlID="btnRefresh" EventName="Click" /> 
      </Triggers> 

     </asp:UpdatePanel> 

     <br /> 
     <asp:Button ID="btnRefresh" runat="server" text="Refresh" OnClick="btnRefresh_Click"/> 
    </div> 

</form> 

Кроме того, я хотел бы убедиться, что вы используете IsPostBack в вашей странице загрузки, которая до сих пор обожженного даже на асинхронной обратной передачи.

protected void Page_Load(object sender, EventArgs e) 
    { 
    if (!IsPostBack) { 
     Clock c = new Clock(); 
     string display = c.GetCurrentTime().ToLongTimeString(); 
     this.Title = display; 
     this.txtDate.Text = display; 
    } 

    } 

    protected void btnRefresh_Click(object sender, EventArgs e) 
    { 
    Clock c = new Clock(); 
    string display = c.GetCurrentTime().ToLongTimeString(); 
    this.txtDate.Text = display; 
    } 
+0

Я скопировал код в DefaultPage и добавил метод обновления в клике, и вся страница все еще обновляется ... мне нужно что-то настроить в файле конфигурации? –

1

Я перепробовал ваш код, и все работает должным образом.

Когда вы нажмете кнопкуRefresh, он обновляет время в Textbox внутри панели обновления, в то же время он также обновляет время в Windows, в строке заголовка.

Кнопка Refresh не обновляет любой контроль вне панели Update

Пожалуйста, смотрите рабочий код

ASPX код

(Примечание: я добавил новый лейбл под названием "lbltemp" за пределами панели обновления)

<form id="form1" runat="server"> 

<div> 
    This is the time : 
    <asp:Label runat="server" id="lbltemp"></asp:Label> 
    <br /> 
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> 
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional" ChildrenAsTriggers="false"> 

     <ContentTemplate> 
      <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> 
     </ContentTemplate> 

     <Triggers> 
      <asp:AsyncPostBackTrigger ControlID="btnRefresh"/> 
     </Triggers> 

    </asp:UpdatePanel> 

    <br /> 
    <asp:Button ID="btnRefresh" runat="server" text="Refresh" OnClick="btnRefresh_Click"/> 
</div> 

Код За

protected void Page_Load(object sender, EventArgs e) 
{ 

    string display = DateTime.Now.ToString(); 
    this.Title = display; 
    this.txtDate.Text = display; 
    this.lbltemp.Text = display; 

} 

protected void btnRefresh_Click(object sender, EventArgs e) 
{ 
    string display = DateTime.Now.ToString(); 
    this.txtDate.Text = display; 
} 
+0

У меня должно быть что-то не так, потому что оно не работает.Название и ярлык, обновление текстового окна каждый раз, когда я нажимаю кнопку. Я заметил ошибку javascript в строке состояния IE8, в которой говорится: «Сведения об ошибке веб-страницы: Сообщение:« Sys »не определено ... –

+0

Daok, Sys undefined означает, что вы не получаете файлы на стороне клиента, загруженные в ваш браузер , Попробуйте проверить настройки web.config, возможно, это отсутствие некоторых настроек обработчика. Кроме того, вы используете http или https? –