Inline Script inside an ASP.NET AJAX UpdatePanel

When you wrap content with an UpdatePanel, it pretty much takes care of everything for you. But it can't do absolutely everything...

Take for example some inline script:

<p>Some html before the script</p>
<script type="text/javascript">
    alert('hi');
</script>
<p>Some html after the script</p>

Inline meaning it appears inline with the rest of your HTML.

First of all -- I'd say it's best not to use inline script if you don't have to. If you can move that script block to the bottom or the top of the page, or to a separate javascript reference, without consequence, then why not keep the script and UI nice and separate? But there are times when inline script is either necessary or just preferred. For example -- check out how you instantiate an instance of Silverlight on your page. That's inline script. It makes sense to keep the script where it is, since that's where you want your Silverlight app to be.

Then, along came UpdatePanel...

The over simplified way of explaining how UpdatePanel does its work on the client is through the innerHTML DOM property. When a delta is retrieved from the server, it finds itself in the existing DOM, disposes of the contents, and then assigns the new content via innerHTML. Thanks to a basically consistent behavior across the major browsers, the new content appears just as if it were there to begin with.

But inline script doesn't work this way. Setting the innerHTML of a DOM element to HTML which contains a script block does not cause that script to execute. The only way to execute arbitrary script dynamically is to eval() it directly, or dynamically create a script element with document.createElement("script") and inject it into the DOM.

So if we had the above HTML+SCRIPT inside an UpdatePanel, whenever it updated, the inline script would simply be ignored.

UpdatePanel realizes that there may be script to be executed. But it only knows about such scripts if they are registered through the ScriptManager's Register script APIs. If you use that API correctly, UpdatePanel once again picks up the slack and takes care of the rest for you automatically.

ScriptManager.RegisterStartupScript(this, typeof(Page), UniqueID, "alert('hi')", true);

UpdatePanel intercepts registrations like these during asynchronous postbacks and sends the content down to the client separately from the HTML. And than the client side PageRequestManager dynamically injects a script element for you. So one solution to this inline script problem is simply not to use inline script. If you use this Register API all the time, it will work whether there is an update panel involved or not.

But I want my Inline Script back!

Alright already. So here is a novel little control that gives you the benefits of inline script without having the draw back of not working in an UpdatePanel.

public class InlineScript : Control {
    protected override void Render(HtmlTextWriter writer) {
        ScriptManager sm = ScriptManager.GetCurrent(Page);
        if (sm.IsInAsyncPostBack) {
            StringBuilder sb = new StringBuilder();
            base.Render(new HtmlTextWriter(new StringWriter(sb)));
            string script = sb.ToString();
            ScriptManager.RegisterStartupScript(this, typeof(InlineScript), UniqueID, script, false);
        }
        else {
            base.Render(writer);
        }
    }
}

If the request is normal, it just renders whatever the contents are as usual. If you happen to be in the middle of an asynchronous postback, it uses the RegisterStartupScript API.

<asp:UpdatePanel ID="up1" runat="server">
    <ContentTemplate>
        <i88:InlineScript runat="server">
            <script type="text/javascript">
                alert('hi');
            </script>
        </i88:InlineScript>
        <asp:Button ID="cmd" runat="server" Text="Update" />        
    </ContentTemplate>
</asp:UpdatePanel>

You get the beloved alert dialog when the update panel updates! Thankfully, because you still put the script element itself in the html, you still get javascript intellisense and all that jazz, too.

Simple, not terribly useful, probably not the best thing to do performance, but could be pretty handy in the right situation.

UPDATE: If you actually use this, you may want to add a check for sm == null as well as IsInAsyncPostBack, so that the control works even if there's no ScriptManager on the page.

70 Comments

  • It's a bit misleading to indicate that inline script is necessary in some cases citing an example for silverlight. It would be far superior to put this code in an external .js file and link an init function for silverlight to the window.onload.

    I personally think the only script tags in a web page should be links to external files in the head of the page. Problem is not enough people are talking about how to do things in external files and with AJAX we now have a new type of speghetti code in our pages, javascript, when it could be so easily kept out of the page altogther. Seperate structure, presentation AND behaviour.

  • Brian -- there's one important difference moving the script to an onload event handler. The page markup is displayed as the browser parses it, and so when the silverlight component is created it could cause an unwanted flickering in the page layout. That, and onload could take a long time to fire. For example it wont' fire until all the images on the page have been downloaded. I for one do not want to wait that long for an important part of my page to be visible. There's ways to limit that problem, but anything except inline script has the potential to cause flickering.

  • There are ways to address this. You could check for the existence of the element you want during load. Getting a reference to the element and trying again until the reference exists. A bit more work is involved but I think it's worth the effort to create a true seperation of behaviour.
    Go back a few years ago and nobody cared about moving presentation (style) out of the markup. In recent times javascript is back in vogue, mainly because of Ajax but unfotunately with this has come a complete disregard for being accessible and unobtrusive. Microsoft have spoken, though, with their Ajax implentation and now Silverlight so millions will follow and I will have to stare at <a href="#" onclick="dosomething()" as well as embedded script blocks within the markup (which truly makes me cringe) for years to come.

  • Checking again until it exists? Do you mean with a setTimeout? That's going to result in the same as if you didn't check until all the markup was parsed. There may still be a flicker.

    I'm all for separation of UI and logic, believe me. The real problem is that the DOM and Browser in general was never intended to be used like we use it today. We have to make due with what we have.

  • Setting a timeout for 1 millisecond is pretty pointless - just use 0 milliseconds. That tells the browser to execute it as soon as possible but not immediately. It's a queuing mechanism. The browser constantly creates 'tasks' that are executed by a single thread. So 0 doesnt really mean 0, it's more like a suggestion. It puts the task on the end of the queue (probably after the task which is parsing the html).

  • I have a bunch of controls with complex javascript "object" components that need to be initialized and have order dependency, previously this was being done with inline javascript created in the render method. But update panel ruined that. So i created a control that provides priority queues and uses a string builder to create one big startup script and register it. So here is my question, once a script has been registered with the ScriptManager can I replace that script with a new one using the same unique id? This doesn't appear to work. The other possibility would be to remove the script from the ScriptManger's script array, but this doesn't seem to work either. Any ideas?


  • Randy -- no, there's really no way to replace a script that's already been registered.

    But I do not understand why are trying to do that. The pattern you should follow is to use the ScriptManager.Register APIs. You pass it the control which owns the script, which is what allows UpdatePanel to be able to successfully execute the script as well as detect whether the script should be executed (a script registered by a control that isn't within an updating update panel shouldn't be executed). Just search for say ScriptManager.RegisterStartupScript and there should be plenty of docs and examples.

    You can also implement the IScriptControl interface if you don't mind requiring a ScriptManager control on the page. You should definitely do this if you're dependent on the ms ajax library.

    If I'm missing something please paste in some code to help me understand :)

  • Works perfectly

    Thanks :-)

  • Randy --- where on earth does it say Startup scripts aren't run in order of registration? That's just not true. If your validator were always after the control it validates in the markup then it should always have its render method called last.

    I'm still having trouble understanding your dependency problem. Why can't you factor these things down into libraries that you can include? Then both controls just include both libraries, with RegisterClientScriptInclude (or RegisterClientScriptResource).

    If the script is completely dynamic and so cannot be externalized, then I think there's a design problem. You should still be able to design it so that the functions are never changing, and all that changes is the parameters you pass it. One control depends on the data of the other. And that can be designed so that order doesn't matter. Both libraries get included, and then startup script initializes the whole shibang with specific parameters to an api defined in the libraries.

  • Yes, after a quick test it appears that the register calls are not the source of my ordering issues. I can't find the page where i read that, maybe I dreamed it. Now that my credibility is completely lost, it appears that the ordering problems are a result of the script executing before the html elements are created, as is the default based on the LoadScriptsBeforeUI property. So the root of the problem is that these js object initialization scripts actually augment the html element with additional functionality, i.e. event handlers, properties, as well as dynamically generated functions. Here is an example of a init script generated by our dateBox:

    var ctl00_MC_SQI_SI_ctl00_DateComp = getObjectById('ctl00_MC_SQI_SI_ctl00_DateComp');
    ctl00_MC_SQI_SI_ctl00_DateComp.IsEmpty = true; ctl00_MC_SQI_SI_ctl00_DateComp.ExtendedType = "LandaDateBox";
    ctl00_MC_SQI_SI_ctl00_DateComp.SelectedDate = new Date('1/1/0001'); ctl00_MC_SQI_SI_ctl00_DateComp.ClearToSpecifiedDate = null;
    function ctl00_MC_SQI_SI_ctl00_DateComp_DateChanged () { return LandaDateBox_ChangeHandler(getObjectById('ctl00_MC_SQI_SI_ctl00_DateComp')); }
    var ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator = getObjectById('ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator');
    function ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator_Validate() { return LandaDateFieldValidator_Validate(ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator); }
    function ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator_ValidateOnBlur(event) { LandaDateFieldValidator_ValidateOnBlur(window.event ? window.event : event, ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator); }
    function ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator_ValidateOnChange(event) { return LandaDateFieldValidator_ValidateOnChange(window.event ? window.event : event, ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator); }
    ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator.evaluationfunction = ctl00_MC_SQI_SI_ctl00_DateComp_DateValidator_Validate;

    This is all being generated dynamically but it is all also unique to this control. I am not sure how this could be externalized.

    My current line of attack is to wrap these init scripts with an function and add that function to the Sys.Application.load event then use the control based registerStartupScript to register that whole mess. This seems to get me most of the way there.

    Thanks for all your help.

  • Randy... if you register your script with RegisterStartupScript then it should always appear after the HTML, unless your controls are after the end of the form element (and if thats the case, just put them inside). Startup scripts always go to the bottom of the form. And during async updates, they always execute after the html has been updated.

  • Kulp -- not sure what you're asking. Are you saying you want this script to be included but you don't want to do the work of registering it through the ScriptManager APIs? Well thats exactly what the control I described in this article is good for...

  • Article is really really helpful, but as i am new to ASP.NET i am getting an error "i88:InlineScript" is not a valid tag.

    Can any one tell me how to register and use that control ?
    Please help i am stuck

  • Parag -- try this
    http://msdn2.microsoft.com/en-us/library/c76dd5k1(vs.71).aspx

  • I was looking for this code...thanks. In my situation i could dynamically load a user control but faild to load or run javascript associated with that user control. with your code I fixed the problem.

    I still have a one more issue though.
    i cannot load a user control that has ajax control (say TabContainer). it works however if i don't use update panel from the calling program (default.aspx). any idea how to fix this issue?

    thanks for the contribution to the asp.net community.
    regards
    achu. (atmonline@yahoo.com)

    "looking for a true web alternative for desktop applications"

  • achu -- why can't you load the control? Are you getting an error or what?

  • yes my TabContainer (Declaratively) defind in the usercontrol. which is dynamically load into the main page say (default.aspx).

    Usercontrol loading with ajax tab details but no visual tab present (I think same situation for all ajax controls due to javascript i believe)

    to summaries....
    1. default page has gridview with buttons on each row,
    2. when user click a button a usercontrol is loaded and display in to a popupcontrol (which is in default.aspx).

    everything work as expected but if I try to load user control that include a ajax control (like tabcontrol) won't work properly.

    things fixed with your codes...
    1. Javascript issue
    2. Postback from usercontrol.

    thanks
    achu.

  • achu -- I'm afraid you'll have to tell me more than just "it wont work properly" :) What does that mean? I can't help if I don't know what the problem is.

  • When i try to load usercontrol from default.aspx the tabpanel not displays the visual tab instead it show only the tab text. how do i fix this without removing updatepanel? please see this simple code to illustrate the problem.

    *****User Control *********





    Tab1 Text





    ******Default.aspx***********









    protected void Button1_Click(object sender, EventArgs e)
    {
    UserControl control = (UserControl)this.Page.LoadControl
    ("UserControl.ascx");
    control.ID = "MyControl1";
    box.Controls.Clear();
    box.Controls.Add(control);
    }


    thanks
    achu.

  • achu -- Sounds like a bug with the Tab panel control, which is part of the AJAX Control Toolkit. I'm afraid my team doesn't have much to do with that, and I can't speak to the source code. I recommend you visit the forums for the toolkit and see if anyone familiar with it can help you, here:

    http://forums.asp.net/1022.aspx

  • i am dynamically creating the script in the button click.
    and registered using scriptmanager..
    ScriptManager.RegisterStartupScript(saveButton, Me.GetType(), WellPATHConstant.Dialogbox, rejectMessageSB.ToString, False)

    could u say me.. when the script is executed... i want this to be on click of that button...

  • Hello,

    I receive this error "The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?)"

    App_Code/InlineScript.cs

    ...using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    ///
    /// Summary description for InlineScript
    ///
    public class InlineScript : Control
    {
    protected override void Render(HtmlTextWriter writer)
    {
    ScriptManager sm = ScriptManager.GetCurrent(Page);

    if (sm.IsInAsyncPostBack)
    {
    StringBuilder sb = new StringBuilder();
    base.Render(new HtmlTextWriter(new StringWriter(sb)));
    string script = sb.ToString();
    ScriptManager.RegisterStartupScript(this, typeof(InlineScript), UniqueID, script, false);

    }
    else
    {
    base.Render(writer);
    }

    }

    }
    ...


    cheers,
    imperialx

  • imperialx -- you need to add the right using statement. StringBuilder is under the System.Text namespace, so add:

    using System.Text;

  • Hello,

    I have a problem I have yet been able to solve. I see you knowledge of scriptmanager, and lifecyle is far better then mine so I ask...

    I have an app. I am working on that dynamically renders usercontrols(its a module application). These usercontrols contain 3rd party UI controls. These controls require script references that get generated when the usercontrols do. So this all works fine until I tried to use AJAX webservices which required a ScriptManager. The ScriptManager(as I understand it) takes over script ref. for the page. So if the SM exisits none of my third party UI controls render correctly.

    Any Ideas?

    Thanks

  • I actually left out one key thing....

    I am dynamically generating these user controls via the 3rd party's CallBack control.

  • LDAdams -- Sorry I'm not really following what the problem is. ScriptManager existing on a page cannot cause scripts to vanish. Perhaps if you package up a small example of your problem and send it to me I can help more (blog at infinity88.com).

  • ldadams -- I assume by "Callback" you mean the ASP.NET Callback feature. And I think what you mean by "using callback to dynamically create our controls on a page" you mean that somehow, someone is using a callback to call a server-side method, which is creating the 3rd party control and manually rendering it into a string, which becomes the callback result. On the client, the rendered html is injected into the DOM.

    Is that what you are saying?

    If so, then this problem has nothing to do with ScriptManager, at all. When you call Render() on a control directly, you are completely by-passing the lifecycle for the control. You can't just instantiate a control and call render, and expect it to work. The control must particpate in the lifecycle of the page by being a part of the control tree -- postback, viewstate, and script registration all depend on this. Doing this custom rendering does nothing more than give you the HTML the control would have rendered, but generating HTML is not the only thing controls do, so you're really on your own at that point.

    As you elluded to you'd have to use an UpdatePanel to get the functionality you want. Its absolutely necessary to do full postbacks to do this in the way you want, and UpdatePanel is what makes full postbacks via AJAX possible.

    You might be able to hack it up by manually ensuring scripts are included when they are needed and continuing to use your callback mechanism, but understand that the control was not designed for that kind of use, and neither were controls in general, so you'd probably go down a path of hacking up things just to work around the issues, and you might run into a big dead end depending on the nature of the control. For example if the control requires postback data (like, it contains a textbox and you need to interact with the textbox value on postbacks), then this isn't going to work at all.

  • great job!
    tx for InlineScript and explanation of the issue with inline JS block

  • Hi,

    I get this error:

    i88:InlineScript Unkown server tag.

    anyone help?

  • Hi.....

    I have a problem that when I use script manager given below my code works fine............ But my update panel is not updating ........ If I am not using the script manager then update panel will update its content...... Can Any one help me....

    protected override void Render(HtmlTextWriter writer)
    {
    ScriptManager sm = ScriptManager.GetCurrent(Page);
    if (sm.IsInAsyncPostBack)
    {
    StringBuilder sb = new StringBuilder();
    base.Render(new HtmlTextWriter(new StringWriter(sb)));
    string script = sb.ToString();
    ScriptManager.RegisterStartupScript(this, typeof(MyTest), UniqueID, "setstyles();", true);
    }
    else
    {
    base.Render(writer);
    }
    }

    Thnaks

  • Abins -- you render base into a string 'script', but then it goes no where. You just have this 'setstyles' call. Whatever it is you are rendering isn't going anywhere. Also why are you capturing the rendering like that in the first place... unless you're trying to handle some real specific scenario you shouldn't need to do that, just let it render normally and it will update.

  • DKoser -- it sounds like you are trying to put the script element inside a control that doesn't support nested content. You'll have to post your markup or email it to me for me to tell you more.

  • Thanks for the article, it help me

  • This may be a simple question but I have no idea how to do it. I want to place inline html between custom asp.net user control tags

    e.g

    testother html


    how do you access the content in between the tags and print it somewhere in your control?

  • Robert -- you need the right attributes. First define a default property with the DefaultPropertyAttribute, then you need the PersistenceModeAttribute, with PersistenceMode.InnerDefaultProperty. This article may be helpful as well:
    http://msdn2.microsoft.com/en-us/library/f820d25y.aspx

  • Hi,
    I test RegisterStartupScript() under ASP.NET 3.5 and found the registered script appears at , Not at the end of the page. WHY?

    Thanks,
    Ricky.















    protected void Button1_Click(object sender, EventArgs e)
    {
    string msg = string.Format("alert('{0}');", "Hi, Button1 is clicked!");
    ScriptManager.RegisterStartupScript(this, typeof(Page), "clcikTest", msg, true);
    }

  • Ricky -- it doesn't. Show me, because thats not how it works for me.

  • ricky -- your code registers the script during an async postback. So how is it the code could 'appear' anywhere? Script that comes back during an async post is just executed, it doesn't 'appear' anywhere. It does get dynamically added to the HEAD as a script element, but just so it can be executed. It doesn't matter at that point if it's in the head or elsewhere, it still executes when it is supposed to.

  • Hey,I have some problems on UpdatePanel with FormView.In my project, a FormView was used within a UpdatePanel to reduce the flicker when user input data. A javascript calendar Control was used to select date.the question is that when UpdatePanel was remove, the calendar control work fine, but when added, failed.
    another problem is that if the initial FormView was set to Edit, It also works fine, but if set to ReadOnly, failed.Here's some code snippet:

  • Ferret -- inline script doesn't work inside an update panel like that, as the article explains. It will work on the FIRST request to the page, but it will not on async updates, which explains why you dont see the problem when you're originally in edit mode.

  • Hello,

    Referring to "public class InlineScript : Control {"

    I assume it is a Web User Control, am I correct?

    Do you have the vb version of the code?


    Thanks!

  • Yenyen -- no, it's just a control. If it were a user control there'd need to be an ascx file. This is a custom server control. Sorry I don't have a VB version but it should be easy enough, its basically just syntax differences. You could always compile it then use reflector to view it in vb.

  • Marco -- I see. Neat trick.. search engines don't always take kindly to being fooled though. If expedia doesnt do it anymore, it could very well because they were asked to stop or get delisted. I'm no search engine guru though, so don't take my word for it.

  • Hi Dave,

    I have a couple questions...

    1. Do you know where I can learn more about what makes a script compatible with the UpdatePanel. From my projects, I have noticed none of the Google API scripts reload after an async Postback even after registering them with the ScriptManager. I have had to encapsulate the markup & script tags inside iframes to get it to work for now.

    2. Do you know what causes this error to be thrown when the postback is caused by a control that triggers an UpdatePanel refresh -> "The state information is invalid for this page and might be corrupted". In my case I allow controls to be dragged & re-arranged in the DOM tree using javascript. But the control tree on the server is never altered since I do all the appropriate arranging in the Render methods only. But it looks like on a async Postback it fails in the LoadPostData method and it doesn't get as far as the control event that triggered the postback.

  • I should also mention that I have already added the call to prevent client caching of the response.

    if (Page.Request.Browser.Browser != "IE") Page.Response.Cache.SetNoStore();

  • khan210182 -- UpdatePanel will only load a script once, for reasons sited by two of my comments up. All controls register all their script resources all the time. That would be terrible if each of their script libraries had to be reloaded each time.

    It isn't correct design IMO to have a script that requires reloading whenever you have to 'redo' something. Imagine if assemblies worked that way... instead of just instantiating a type in that assembly when you needed it, you had to reload the entire assembly and then it 'automatically' did what you wanted. Terrible.

    Script resources are only loaded once. Any scenario where you need to load it twice can be redesigned to have a library that never changes but can be called with different data. Its the DATA that changes on post backs, not the logic that deals with the data.

    That said, you can't control google scripts obviously.. so instead just make UpdatePanel 'think' its a new script each time by appending a timestamp onto the end of the querystring (googleapi.js?t=).

    As for #2 -- it depends on what you are doing. Its ok to move elements around as long as you aren't changing their IDs or Names. Also, if you are raising postbacks with __doPostBack, its important to utilize event validation, or turn it off. Search on event validation for more info on what that is.

    I suggest you simply turn off partial rendering to test the problem. Usually an error like that would fail on a regular postback, too, and you're just making it harder to see with partial rendering enabled. That is always a good test to do by the way - if you page doesn't work with regular postbacks, partial rendering probably won't either.

  • Hi Infinite Loop,

    1. I have created Control as you explained
    2. Added control to the web page.
    3. It gives me error while adding to the Form Unhandled excetpion Object reference not set to an instance of an object.
    4. If I add script then it is showing
    Does not have a public property name script....

    Please help me out I am stucked ...

  • Make sure you have a script manager on the page. And make sure you typed the control code exactly as I showed it, it sounds like you did it wrong.

  • I have a page with more than one update panel, gridviews, textboxes, ect. The buttons on this page won't cause a postback. I have tried declaring new buttons, strip the page down to only one section, but NOTHING. The page won't even refresh. It's like clicking on a button in a windows app and the button does not have any event linked to it.

    I'm wondering if the postback function is not being registered with the scriptmanager?? As I understand it there is a sort of fixed postback function in javascript that the button execute automatically?

    Funny thing is... I have other pages with the same setup, but with lest controls and they seem to work fine. Also if I have a dropdown with it's AutoPostBack property set to TRUE, it does a post back.

    Hope some here could help.

    Thanks

  • NeCroFire -- odd, but probably something simple. Are you sure there's no javascript error occuring when you click the buttons? Can you post a quick snippet of what your markup looks like?

  • Hi there,

    How can I change the script dynamically? I mean, from the codebehind.

  • Emerson -- the benefit of the control is that it can be declared. If you're doing it dynamically anyway, why not just use the ScriptManager APIs to register it?

  • Thank you very much for this, it helped immensely. Very well explained in regards to the relationship between scripts and the DOM.

  • Tankut -- once the page is loaded, you can't use document.write. It isnt a matter of "where" it is called -- script has no concept of location once the html has been processed. You just can't do it -- thats how the browser works. So if you want ajax, you will have to convert to the script to support it, such as by using innerHTML to insert content after the first time instead.

  • hi,

    i have a usercontrol,inside tht user control i have some ajax controls.i am trying to load the user control with _dopostback() so tht i can get the delayed load logic.what happens is i tried the code for grid populate in the _dopostback(controlname).click event
    what happens is i get the

    contains multiple calls to Sys.Application.notifyScriptLoaded(). Only one is allowed error but if i load the usercontrol on pageload and and try the same logic it works.

    can u help me?


    can u help me

  • You are a LEGEND, I was racking my brain about this all day!!!

  • thanks for you post.

    but i found a problem using this with Google Chrome.

    the issue is: if we use a "for" statement in javascript inside the InlineScript control, e.g:

    var count=2;
    for(var i=0;i<count;i++)
    {
    alert(i);
    }

    an error occurs in Chrome's console:
    Uncaught SyntaxError: Unexpected end of input

    i found the problem is cause by the "count" variable.

    i don't know it is an chrome's problem or ajax.net's problem.

    could you have a check with it?

    thanks in advance! please let me know if you have any idea about it. my mail is seiecnu(at)gmail.com

  • Hello,
    Tried the code and indeed I get the alert firing...

    BUT my situation is a bit awkward.

    I basically have a bunch of headlines in the left column when clicked load up in the right column update panel - works fine
    The article data is contained within a SQL database and displayed in a details view on the page.

    Recently i've been tasked with displaying a countdown "weeks to go" article. I've got an external .js file that does what I need but when i try to overwrite the div using getElementById it complains - "is null or not an object". It's because it's the 2nd article and the div doesn't seem to exist in the DOM yet.
    Does that make sense?
    Thanks

  • Waseem -- I'm afraid I'll need more details. Can you break it down into some code samples, even if it is just psuedo code?

  • Can anyone plz tell me how to call a .js file function on the button click of a content page which is Ajax update panel? plz its very urjent for me.

  • HBBob -- sounds like you need a @register directive. ASP.NET is complaining it doesn't know what the 'i88' tag prefix is. If you already have that, perhaps you put in the wrong namespace. If you didnt, perhaps it is compiling -- is it in the project, or if its a website style app, is it in app_code?

  • You rock best brain i have seen ever :)

  • I had been using something like this for a bit and wanted your opinion.

    I have a situation where I have many update panels, so to skip the heavy server transfer, I am using webmethods to generate and drive my grids through passing only a request and retrieving html.

    In this situation, if a server request is made to an update/insert, I want to update this grid, so I've been registering a request to update this on asynch postback. I use the db info already populated on the server at the time and generate the html, then I send the HTML back to a function that updates the grid, much like the update panel does but without any of the overhead.

    Essentially (ultra psuedocode):

    UpdateButton_Click:
    formView.UpdateItem()

    ...

    FVODS_Updated:
    if [success]
    data = GenerateHtmlFromDS(ODS);
    RegisterStartupScript(..."SetData(' & data & ')" );



    Do you see any issues with this? It's been the only way I could find to speed up a page that used to have about 25 modals driving the data. The modals are still slow to load/close due to the number of update panels required to drive them, but the grids run very well.

    Thanks!

  • clduvall -- Perhaps I am missing something, but I don't see how what you are doing improves performance. You seem to be performing a full postback anyway, so all the overhead associated with an updatepanel is already happening. You said you use a WebMethod but UpdateButton_Click looks like a server-side postback event, no?

  • The performance improvement comes on separating the view from the webform model. I can now select a row in the grid and perform other client-side functions such as requesting the details without posting back to the server. That helps a lot given the complexity of the page.

    A normal postback select$ call on the gridview was transferring about 150k of data and could take upwards of 10s due to the number of update panels. Now the total transfer is between 1k-5k and is about 0.2s.

  • clduvall -- I understand the performance benefit of not posting back, but from the code you posted, it looks like you are posting back.

    You should take a look at ASP.NET AJAX 4.0 Client Templates. There's a preview of it available on codeplex. It would allow you to make it even better, because you can send just the data to the client, and have the client responsible for generating the HTML from the data, but in a way that doesnt involve messy innerHTML or DOM operations.

  • I did a poor job of explaining. I definitely have some asych postbacks controlled by ASP, specifically the form views.

    Specirfically for my grids:
    When I select a row, I call a webmethod which sends about 700bytes to the server, then receives a modest amount back. The whole process is very minimal (albeit more manual than I'd like).

    When I'd allow WebForms to manage this (Select$ on the grid), it would send the entire viewstate (which I've minimized greatly thanks to your article) as well as perform a lot of binds/rebuilds that I didn't ask for (I wish updatemode on an update panel actually did what I think it should do).

    The other benefit is that if I want to refresh a grid, a simple call to the webmethod accomplishes this without touching anything else on the page.

    Mind you, this was all built with an unreasonable timeline, so I didn't have time to really look for alternate solutions to work. I got the idea from ScottGu's blog - http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx - and from there I just built around this concept.

    There are a few buttons below each grid, which launch Modals [client requirement] to perform Add, Edit(s), Delete, and/or Copy functions. This is where the update panels come into play. When a button is clicked, the full viewstate goes back, plus some other data from the UpdatePanels and it is quite slow. My grid solution avoids that for every selection/detail retrieval.

    I'll definitely look into the 4.0 client templates. I was interested in moving toward MVC2 on the next release, it appears to be flexible and accomplish a lot of what I've manually created.




  • I donot know if its right or wrong to use inline scripting...but I have developed a lot of code using inline scripts and this article really solved my issue....

    Great Idea by the way...awesome...
    thanks dude........ you really made my day!!! cheers!!!

  • Thanks a lot..... You saved my day.............. Really useful code.....

  • I've created a dll with the control and I'm trying to use this way:



    "ClasesPropias.dll" contains the "InLineScript" class and is in the bin directory of the application. However I'm getting the following error: "Bloque de servidor incorrecto" ("Wrong server code"?).

    Am I doing something wrong?

Comments have been disabled for this content.