Load Javascript function from update panel - c#

I have the following code -
protected string Term
{
get { return this.ViewState["Term"] != null ? (string)this.ViewState["Term"] : ""; }
set { this.ViewState["Term"] = value; }
}
Then set Term -
public void populateTerm()
{
Term = "Test";
ScriptManager.RegisterStartupScript(this, GetType(), "term","useTerm()", true);
}
Then in Javascript can use Term -
function useTerm() {
var Term = <%= Term %>;
// use Term
}
This works fine when the page is getting reloaded on the button click that was firing populateTerm(). However I have since moved the button into an updatePanel, so because the entire page is not getting reloaded on button click (only the update panel), this means that useTerm() is not called and <%= Term %> is null.
If I remove the updatePanel code it works fine. How can I get this to work with the updatePanel?

Assuming that the function useTerm is in you aspx page, you can move that script block within the UpdatePanel ContentTemplate.
An alternative would be to change the JavaScript function so term is passed in as a parameter:
function useTerm(term) {
// use term
}
and then to call it with the latest value of Term:
public void populateTerm()
{
Term = "Test";
string script = string.Format("useTerm('{0}');", Term);
ScriptManager.RegisterStartupScript(this, GetType(), "term", script, true);
}

Related

How can i store the selected tab on a RadTabStrip that can be returned to on back button click

I currently use a hidden input field that is assigned the value of the tab that has just been selected, via javascript, like so:
function onTabSelecting(sender, args) {
var tab = args.get_tab(); //get selected tab
document.getElementById("MainContent_hdnPreviousTab").value = tab.get_text(); //assign value to hidden field
if (tab.get_pageViewID()) { //ignore
tab.set_postBack(false);
}
}
I then use this assigned value when the page is returned to, on client-side (ajax) PageLoad() event:
<script type="text/javascript" language="javascript">
var runOnce = false;
function pageLoad() {
if (!runOnce) {
var lastTab = document.getElementById("<%= hdnPreviousTab.ClientID %>");
if (lastTab.value) {
if (tabStrip) {
var tab = tabStrip.findTabByText(lastTab.value);
if (tab) {
tab.click();
}
}
}
runOnce = true;
}
}
</script>
Currently in IE this works fine (I know right?), the value that was previously set in javascript is still there and i am able to lcoate the tab that the user left the page on. However in FF, Chrome, etc. i have no such luck. The hidden field is returned to it's empty state (value = "") regardless of utilising viewstate or not.
Very curious as to whether anyone has an alternative method that would be appropriate in this situation. Please let me know if this is unclear.
Many thanks.
You could use localstorage.
localStorage.setItem('tab', value);

How to Check if ListBox is Empty on Client-Side

I created a javascript confirm as below.
<script Type="Text/Javascript">
function CheckListBox(lvi)
{
if(lvi == "")
{
if(confirm("Are you sure?"))
{
return true;
}
else
{
return false;
}
}
}
</script>
I need to test if the ListBox.Items control is empty... I already made reference on my aspx page
<script language="javascript" type="text/javascript" src="/JS/confirm.js"></script>
I want to know how to call it on my aspx.cs page . . . So I can pass the parameter:
string oi = Listbox_Clubes.Items.Count.ToString();//Its the parameter I want to pass
See this link for how to execute javascript from code behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "CheckListBox(" + Listbox_Clubes.Items.Count.ToString() + ");", false);
}
Note: you must add a ScriptManager control in aspx page.
For your javascript, you can get the value without the code-behind (this assumes the script code is in the same page, in order to get the client ID):
<script>
function ClickListBox() {
if ($("#<%= Listbox_Clubes.ClientID %>").val() === null) {
if (confirm("Are you sure?")) {
return true;
}
else {
return false;
}
}
}
</script>
Similarly, you don't use javascript to validate on the server side. The code you posted will return all items in the ListBox. Here is one way to get the count of the number of selected items (I'm using .ToString() based on the OP code example):
string oi = Listbox_Clubes.Items.Cast<ListItem>().Where(i => i.Selected).Count().ToString();
However, there is no reason why you would get this value and pass it back to the client-side to do validation (what it sounds like you want to do in your post). Mainly because this involves a post-back, and client-side validation, by its nature, should occur before post-back. Also, you will still need to do server-side validation, even when you have client-side validation.
Related: in the code-behind, you can test to see if anything is selected by:
bool hasValue = Listbox_Clubes.SelectedItem != null;
The .SelectedItem returns the selected item with the lowest index in the list control. When nothing is selected, this value is null... so you know if the value isn't null, then at least one item was selected.
If you want to require that they choose at least one item, you can use a RequireFieldValidator and let that handle both validations. If you haven't done much with ASP.NET validators, that would be one good thing to read up on.
It sounds like you probably should read more about client-side validation and server-side validation and how to use them... because it seems like you are mixing them up.
The count code is a modified version of code in ASP:ListBox Get Selected Items - One Liner?

jquery function doesn't work when called from usercontrol

I have an aspx page which holds 2 user controls
UC1: Edit page - this has the fields for editing or data entry.
UC2: Notification page - this has a simple message box with jquery function
in my aspx i have this function:
public void ShowMessage(string status, string message)
{
Notification1.Message = message; //this is my user control UC2
Notification1.Status = status;
Notification1.DataBind();
}
now when my aspx page needs to show a message this works fine, but when i want the user control 1 to show a message like (invalid field, or wrong amount) it doesn't do anything. Now it gets called but jquery just doesn't react to it.
in UC2 -notification user control this is what I have:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
<script type="text/javascript">
function showMsg(classname) {
$("#MsgBox").attr('class', classname);
$("#MsgBox").show().delay(5000).fadeOut();
}
</script>
<div id="MsgBox" class="info"><asp:Label ID="lblMessage" runat="server" /></div>
codebehind
public string Status{ get; set; }
public string Message { get; set; }
public override void DataBind()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
and this is how i call the function from user control to aspx page:
((myaspxpage)this.Page).ShowMessage("error", "This is my error message.");
any help will be much appreciated! and if further details is needed just let me know.. Thanks in advance.
**EDIT: I tried putting the jquery and message box inside my Edit page to see if it would work that way and it doesn't So it seems that jquery is not working well within a usercontrol??
Move your codes of DataBind() method into OnPreRender. This should work. The reason is that you don't know which code from which step of your page cycle (init, load, bind, ...) is going to change the Message property.
Like in your case it seems you have a button click event where you are setting the Message property from. This is too late because your Notification1 control is already databound.
Leaving it as the latest stage makes it work:
protected override void OnPreRender()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
I found the error is what that my button that was calling the function in aspx page was inside an update panel and i needed to add a trigger event to make it work.. Thanks everybody for the help it was that update panel causing the error :(

How can i determine PostBack value in window.onunload?

In our project we are deleting something after the user left the page. We are using window.unload event for doing this.
window.onunload = function() {
// delete something
}
We are generally using buttons, linkbuttons..etc in UpdatePanel so we hadn't needed to check Page.IsPostBack property.
Today we realized that we used some buttons out of UpdatePanel and this situation had produced some errors. After that we decided to change our method, defined a global variable (var _isPostBack = false), at the top of the our page and:
window.onunload = function() {
if (_isPostBack) {
_isPostBack = false;
return;
}
// delete something
}
Altought i set the g_isPostBack in Page_Load, g_isPostBack didn't change. I tried "RegisterClientScriptBlock", "RegisterOnSubmitStatement" and "RegisterStartupScript" methods. Register methods were called before the onunload event but _isPostBack was set after onunload event had triggered...
if (IsPostBack)
{
Control c = MyClass.GetPostBackControl(this);
bool inUpdatePanel = ControlParentForUpdatePanel(c);
if (!inUpdatePanel)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = true;", true);
}
}
Is there anyone to help me?
that's the trick...
if you add onsubmit attribute to your form tag:
<form id="form1" onsubmit="return yourPostBack()">
and than write your own function:
function yourPostBack()
{
_isPostBack = true;
return true;
}
and finally in the page load:
if (IsPostBack)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = false;", true);
}
with this method you can understand that it is postback or not, in window.onunload
I hope i am on the right track here,
As i understand,
the OnUnload() is ClientSide,
and therefore you don't have the server objects
what you can do... is save the value in a hidden field.
As i am used to PHP you can even embed the value in a Javascript variable
Dont know if this applys to ASP.NET:
<script language="javascript">
var MyServerVariable = "<?PHP echo MyServerVariable ?>"
if(MyServerVariable == "Blah...")
{
}
</script>
translates to
<script language="javascript">
var MyServerVariable = "VALUE"
if(MyServerVariable == "Blah...")
{
}
</script>
But same thing can be done with <asp:Label /> , i am sure...

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I am having what I believe should be a fairly simple problem, but for the life of me I cannot see my problem. The problem is related to ScriptManager.RegisterStartupScript, something I have used many times before.
The scenario I have is that I have a custom web control that has been inserted into a page. The control (and one or two others) are nested inside an UpdatePanel. They are inserted onto the page onto a PlaceHolder:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
This is the only update panel on the page.
The control requires some initial javascript be run for it to work correctly. The control calls:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
and I have also tried:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
The problem is that the script runs correctly when the page is first displayed, but does not re-run after a partial postback. I have tried the following:
Calling RegisterStartupScript from CreateChildControls
Calling RegisterStartupScript from OnLoad / OnPreRender
Using different combinations of parameters for the first two parameters (in the example above the Control is Page and Type is GetType(), but I have tried using the control itself, etc).
I have tried using persistent and new ids (not that I believe this should have a major impact either way).
I have used a few breakpoints and so have verified that the Register line is being called correctly.
The only thing I have not tried is using the UpdatePanel itself as the Control and Type, as I do not believe the control should be aware of the update panel (and in any case there does not seem to be a good way of getting the update panel?).
Can anyone see what I might be doing wrong in the above?
Thanks :)
Well, to answer the query above - it does appear as if the placeholder somehow messes up the ScriptManager.RegisterStartupScript.
When I pull the control out of the placeholder and code it directly onto the page the Register script works correctly (I am also using the control itself as a parameter).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
Can anyone throw any light on why an injected control onto a PlaceHolder would prevent the ScriptManager from correctly registering the script? I am guessing this might have something to do with the lifecycle of dynamic controls, but would appreciate (for my own knowledge) if there is a correct process for the above.
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
What is your script actually doing?
Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
Have you tried Firefox and Firebug - is that reporting any script errors?
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje
This part of what i posted some time ago here.
Hope this help... :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
DO NOT Use GUID For Key
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
and if you want to do that , call Something Like this function
public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2", "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);

Categories