I'm using the GreyBox js library to display a popup. To give some more general context I've rewritten a solution that was in VB.NET to C#. The code is essentially identical in both, just with the differing syntax used in both. However, the following works in the VB.NET solution but not the C# version:
VB
script = String.Format("GB_showCenter('My Caption', '../MyPage.aspx?number={0}&state={1}&ID={2}',300,600 );", num, MyLabel.Text, Label_id.Text)
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), Guid.NewGuid().ToString(), script, True)
This works and when a button is clicked it navigates the user to a new page that has the size restricted. However, the following doesn't work.
C#
script = String.Format("GB_showCenter('MyCaption', '../MyPage.aspx?number={0}&state={1}&ID={2}',300,600 );", num, MyLabel.Text, Label_id.Text);
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), Guid.NewGuid().ToString(), script, true);
What should happen is when I click a link button the text in the MyLabel is evaluated and if the text is the correct one then the string 'script' is set appropriately and registered with the scriptmanager. Running through with the VS2010 debugger this is all happening as expected. However, the user isn't navigated to a new page called 'MyPage.aspx'. The url stays the same and the page goes blank.
What's more interesting is that if I click the scroll bar the current page is briefly displayed along with the new popup shown above it on the same page. So my current theory is that it's something to do with how the javascript is called from the c#. Any ideas?
UPDATE
I went through with the vs2010 debugger and decided to see if MyPage.aspx was hit at all. It wasn't, as I expected. However, I then thought that perhaps it wasn't firing it's Page_Load event. So I added in:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Load += Page_Load;
}
I set a breakpoint on the Page_Load event of MyPage.aspx and this was now being hit. All the logic was being run through correctly, but I was still getting the same issue (blank page etc, url not changing to MyPage.aspx etc).
I found the answer, though it's not really related to GreyBox specifically. I'd incorrectly made something a script when it should have been a link and added incorrect attributes. The type was text/javascript when it should've been text/css. This seemed to make the difference. To give more context I had the following:
HtmlGenericControl Link5 = new HtmlGenericControl();
Link5.TagName = "script";
Link5.Attributes.Add("href", ResolveClientUrl("~/MyApp/Greybox/gb_styles.css"));
Link5.Attributes.Add("rel", "stylesheet");
Link5.Attributes.Add("type", "text/javascript");
Page.Header.Controls.Add(Link5);
The 'TagName' should've been 'link' and the Link5.Attributes.Add("type", "text/javascript") should've been 'text/css'.
Related
I encountered some weird behaviour today and I was hoping someone could shed some light on it for me because I'm perplexed.
I have a couple of methods I use to interact with the ui for the sole purpose of displaying error/success/warning messages to the user.
Here is one of them
public static void Confirm(string text)
{
var page = (Page)HttpContext.Current.Handler;
var uiConfirm = new HtmlGenericControl("div")
{
ID = "uiNotify",
InnerHtml = text
};
uiConfirm.Attributes.Add("class", "ui-confirm");
page.Master.FindControl("form1").Controls.AddAt(2, uiConfirm);
}
This works perfectly fine except for one nuance I encountered this morning and I was hoping someone could shed some light on it for me.
I am working on your run of the mill profile editing page. In this page, I am binding a couple of dropdownlists (country, province/state) on page load. I have a submit at the bottom and a click event that fires to update the information, then call the method above to notify the user that their information was successfully updated. This works the first time you click the submit button; the page posts back, the information gets updated in the database, the dynamically added div gets popped in, confirm message is displayed and all is good. However, if you then click the submit button again, it fails stating SelectedItem on the dropdowns I'm binding in the page load is null (Object reference not set to an instance of an object). The dropdown is actually wiped for some reason on the second postback, but not the first.
In sheer desperation after trying everything else, I decided to take out the call to the confirm method... and strangely enough the error disappears and I can update the information on the page as many times as I like.
If I add a generic control statically to the page I'm working on, and change my method slightly so that instead of adding a generic control to the form dynamically it just finds the generic control on the page, that does no produce the same error.
The problem also goes away if I remove the two dropdowns from the page or just stop interacting with them.
Why on earth would adding a dynamic control to the form wipe my dropdowns on postback?
I think you should consider using the PlaceHolder class in your MasterPage, the AddAt(2, uiConfirm) is going to bite you and probably is:
Markup:
.......
<asp:PlaceHolder id="PlaceHolder1"
runat="server"/>
......
Code-behind:
public static void Confirm(string text)
{
var page = (Page)HttpContext.Current.Handler;
var uiConfirm = new HtmlGenericControl("div")
{
ID = "uiNotify",
InnerHtml = text
};
uiConfirm.Attributes.Add("class", "ui-confirm");
//may need to change depending on where you put your placeholder
Control placeHolder = page.Master.FindControl("PlaceHolder1");
placeHolder.Controls.Clear();
placeHolder.Controls.Add(uiConfirm);
}
I have an ASP.NET user control that I want to write some dynamic Javascript to (basically a JQuery call to open an accordion node).
To complicate matters, I'm using history points. In a nutshell, I need to open a JQueryUI accordion based on a value in the history point data stored in the URL.
I've got the part that sets the history points working, and I can step through my code (below) as I navigate the history. The problem is, in this example, my script never renders on the page.
protected void uxScriptManager_OnNavigate(Object sender, HistoryEventArgs e)
{
if(!String.IsNullOrEmpty(e.State["activeTab"]))
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "xScript", "alert('Hello,world!');", true);
}
}
Am I doing something wrong?
Addendum
I've been tinkering, and it seems like my call to register the clientscriptblock works fine in other events...but in the Navigate event for the scriptmanager, I can't write new script out to the page. I'm thinking what I'm trying to do isn't possible...
From what I've found, it doesn't look like it's possible to write new client script out to a page - or change values in an existing script block - on the Navigate event. I'm noting this in case anyone else tries to do the same thing.
CORRECTION
I found out it is possible to do what I want!
I need to set the history point in an early part of the page lifecycle
I need to set the dynamic script in the RegisterStartupScript method for the page
(Ivan's post pointed me in the right direction, so I've flagged his post as the answer)
It looks like you need to add script by calling ScriptManager.RegisterStartupScript method to show elements on page:
ScriptManager.RegisterStartupScript(this, this.GetType(), this.ID,
""alert('Hello,world!');", true);
Here's the thing
I added a button to a webpart which saves some fields to MS-Excel.
var btn = new Button { Text = title, CssClass = css };
btn.Click += (sender,args)=>action();
Container.Controls.Add(btn);
This code is located inside OnInit() method in the WebPart. actionis the Action which does stuff, in this case:
Something.FillExcel(MyData);
Something.SaveExcel();
So what happens is, I click the button, it acts like doing the usual partial postback, and does absolutely nothing. I thought it could be something in the Fill/Save code, then I tried forcing an error just to see if it gets there. It seems the click event never fires, or, if it does, it doesn't run my code (?).
Here's the html, just in case:
<input type="submit" name="ctl00$m$g_b4af4370_c016_4712_9d60_fc8ca077a068$ctl359" value="Enviar Formulário" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_b4af4370_c016_4712_9d60_fc8ca077a068$ctl359", "", true, "", "", false, false))" class="button" />
What could be happening?
Thanks in advance!
EDIT: After Cos Callis answered, I put my code inside OnLoad() instead of OnInit(). Here's new code:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var btn = new Button { Text = title, CssClass = css };
btn.Click += new EventHandler((sender,args)=>{
if (myform.Page.IsPostBack)
{
excel.FillExcel(); excel.SaveFile();
}
});
container.Controls.Add(btn);
}
I'm now getting a javascript error: SCRIPT5022: Sys.WebForms.PageRequestManagerServerErrorException: The given key was not present in the dictionary.
Because you are attempting to act on the INIT rather than the load, the data has not yet been attached at the server.
You should find this review of the life cycle of a web request in ASP.NET useful:
http://msdn.microsoft.com/en-us/library/ms178472.aspx.
Here is the relevant extract:
Initialization
During page initialization, controls
on the page are available and each
control's UniqueID property is set. A
master page and themes are also
applied to the page if applicable. If
the current request is a postback, the
postback data has not yet been loaded
and control property values have not
been restored to the values from view
state.
Load
During load, if the current request is
a postback, control properties are
loaded with information recovered from
view state and control state.
During initialization the control "exists" but has not yet been loaded with data from the postback. If you you move your code to "OnLoad" you should achieve the disired results. (Don't forget to wrap that in "if(IsPostback)")
Cheers,
CEC
//added resource: After posting my answer I thought you might find this article useful as well:
http://encosia.com/2007/10/24/are-you-making-these-3-common-aspnet-ajax-mistakes/
Sorry guys found out it was an error inside FillExcel(). I thought I would get that asp yellow page but instead it gives me a script error.
Maybe another common mistake for ajax/jquery/sharepoint newbies.
I'm accepting Cos Callis' reply as answer because he did answer everything I asked.
I've got a page with a Timer that is being used as a trigger on an UpdatePanel. The page also contains a TabContainer and several TabPanels. Look at this question for more information. Basically, I've got an UpdatePanel as the element in each TabPanel's ContentTemplate, and the UpdatePanel is triggered by the Timer.
My page displays data by reading a database on each tick. I've got the following code running on each Timer.Tick in my codebehind:
protected void timeRefresher_Tick(object sender, EventArgs e)
{
UpdateLivePageTitle();
}
The UpdateLivePageTitle() function reads the new information from the database and sets Page.Title accordingly. However, this information is of course not sent to the browser because there is no full page postback--only an async postback to the update panels. As a result, my page title is not being updated until the whole page is being posted back, which destroys the purpose of using UpdatePanels in the first place.
I figure there would be a way to do this by using the document.title JS element and call that from within UpdateLivePageTitle(). But as of now, I haven't been able to figure out how to do this. I tried using the following in my UpdateLivePageTitle() function:
string updatePageTitleScript = String.Format("document.title = '{0}'", newPageTitle);
ToolkitScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "UpdatePageTitle", updatePageTitleScript, true);
But the result of this was that my TabContainer stopped rendering. I'm also not sure that would work with the async partial page postbacks, either. Any ideas?
Thanks!
You forgot the ; from your script.
Oh, and if I remember correctly, the framework should be able to update the title if you just set Page.Title.
In my web application when i upload a video and click the save button, if the video is uploaded i write the code to display the message video is uploaded. My code is as follows:
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", false);
When the alert box appears is comes with a white background. I clicked on ok button in that alert box but the page is not going back to the previous page it is showing the same white space.
Can you solve the problem.? If you not understand i will explain clearly.
In local it is working fine but when i update in online it is not working.
Hai sridhar,
I found an answer for your prob
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);
change false to true
or try this
ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);
The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.
Instead use the .NET 2.0 Page.ClientScript.Register* methods.
- (The ClientScript property expresses an instance of the ClientScriptManager class )
Guessing the problem
If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.
Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.
See if the below helps you:
I was using the following earlier:
ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");
After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:
ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);
This is working perfectly fine.
(It’s .NET 2.0 Framework, I am using)