.net - How do you Register a startup script?

5k Views Asked by At

I have limited experience with .net. My app throws an error this.dateTimeFormat is undefined which I tracked down to a known ajax bug. The workaround posted said to:

"Register the following as a startup script:"

Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value)
{
if (!this._upperAbbrMonths) {
this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
}
return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
};

So how do I do this? Do I add the script to the bottom of my aspx file?

3

There are 3 best solutions below

3
On BEST ANSWER

You would use ClientScriptManager.RegisterStartupScript()

string str = @"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { 
    if (!this._upperAbbrMonths) { 
        this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
    }
    return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
 };";

if(!ClientScriptManager.IsStartupScriptRegistered("MyScript"){
  ClientScriptManager.RegisterStartupScript(this.GetType(), "MyScript", str, true)
}
0
On

Put it in the header portion of the page

0
On

I had the same problem in my web application (this.datetimeformat is undefined), indeed it is due to a bug in Microsoft Ajax and this function over-rides the error causing function in MS Ajax.

But there are some problems with the code above. Here's the correct version.

string str = @"Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) { 
    if (!this._upperAbbrMonths) { 
        this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);
    }
    return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));
 };";

ClientScriptManager cs = Page.ClientScript;
if(!cs.IsStartupScriptRegistered("MyScript"))
{
    cs.RegisterStartupScript(this.GetType(), "MyScript", str, true);
}

Put in the Page_Load event of your web page in the codebehind file. If you're using Master Pages, put it in the your child page, and not the master page, because the code in the child pages will execute before the Master page and if this is in the codebehind of Master page, you will still get the error if you're using AJAX on the child pages.