How to preserve static variable values in JavaScript functions on postback? - javascript

I have this sample below:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script type="text/javascript">
function test(){
if (test.initialized=='undefined'){
test.initialized = 'true';
}
alert(test.initialized);
};
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Button ID="btnPostBack" runat="server" Text="Post back" OnClientClick="test()" />
</asp:Content>
When I click post-back on the page, I found out that the variable initialized -which is defined on the function itself- is loosing its value and becoming 'undefined' again.
Is it possible to keep those static values once they are defined and make them unaffected from any post backs on the page?

You could add them as a query string or keep them in a cookie.

Maybe you want to do something like this. I also think that you are confusing test function with test object.
var initialized = false;
function test(){
if ( !initialized){
initialized = true;
}
};
alert(initialized); // false
test();
alert(initialized); //true

javascript is going to be re-executed on postback as the page reloads (unless you are using update panels).
to preserve a client side value, write the value into an asp hidden field using JS, and don't render the javascript if IsPostBack is true so that it doesn't get overwritten on postback

I think using partial-post back is a way as well.
If it is not possible, only by using Java script I think cookies can be another way as long as they are not turned of by the user.
My feeling is the best way is to design the page in a way that I would not need to store it :)

You could add a hidden field and set the value of this? I think this way it'll be preserved in the viewstate, and you can load its value back into your variable with something like:
var p = '<%=blah.Text%>';

Related

Control is not declared. It may be inaccessible due to its protection level

I'm really stuck and I've tried all the other examples but nothing works. I'm fairly new to ASP.NET but learning fast!
I want to use the jQuery datepicker and I am inserting this script
<script>
$(document).ready(function () {
$(function () {
$("#" + '<%=txtDOB.ClientID%>').datepicker();
});
});
</script>
and my control on the aspx page is
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>
As soon as I close the the server tag %> the red line appears under the txtDOB control and says:
txtDOB is not declared. It may be inaccessible due to its protection level.
I've made the class public in the code behind but doesn't make any difference. I've also moved the script to the bottom of the page. If I change the asp textbox to a HTML input it works fine.
It will work fine with an ASP.NET TextBox as you have used. Therefore it must be to do with where your control is located. For example, if it's inside a Repeater or Grid, you will not be able to use its ID directly like that, since the framework will generate unique ids for each row at runtime.
Create a simple webform with no other controls on the page, and you will find it works just as you have it.
Try using static ID mode instead:
<script>
$(document).ready(function () {
$("#txtDOB").datepicker();
});
</script>
It makes the client script easier (especially when you move it to an external .js file to take advantage of caching), and is an easy change to the ASP control:
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server" ClientIDMode="Static"/>
You could use a different type of jQuery selector to select for that ID as follows:
<script>
$(document).ready(function () {
$("input[id$=_txtDOB]").datepicker();
});
</script>
That selector will account for the text that is being appended to the beginning of your ID due to the use of your CreateUserWizard control. It is cleaner than the way you are currently doing it, and you can use your original HTML.
<asp:TextBox ID="txtDOB" CssClass="form-control" runat="server"></asp:TextBox>

Unable to call a function while using master page in Javascript at checkbox checked change event

I was trying to call a function when the checkbox status changes, it calls without a masterpage. I have tried the following code:
<script type="text/javascript">
$(function () {
$('#cbOption1').on('change', PublishToPreferredZerker);
});
function PublishToPreferredZerker() {}
</script>
[...]
<asp:CheckBox ID="cbOption1" runat="server" style="text-align: left"
Text="Publish the job to particular Zerker or a group of the Zerkers." /><br />
The function is not called when using MasterPage.
Note cbOption1 is not the client ID, but the ID for the server side.
You need to do something like (Use Control.ClientID Property to get the id for HTML element):
$('#<%=cbOption1.ClientID%>').on('change', PublishToPreferredZerker);
The code
$('#cbOption1').on('change', PublishToPreferredZerker);
finds the control with id cbOption1 and then acts on that control
But when using this code on a master page, the control id does not remain cbOption1.
It is prefixed by master page content Id.
something like ct$001cbOption1
To make it work when using master pages use code like this to find the clientId for the control :
$(#"<%= cbOption1.ClientID %>").on( .... )
I got success while I added below code on Page load function.
cbOption1.Attributes.Add("onChange", "javascript:PublishToPreferredZerker()");
Javascript function
function PublishToPreferredZerker() {}
Also I have tried above answers but not get required output.
Thanks,

Referencing inline scripts from update panels in ASP.NET

I am trying to work around an issue with using inline scripts in update panels. The issue is something I might commonly solve by using Sys.Application.add_load() or creating a RegisterStatupScript() script with the ScriptManager. However, neither solution works in this case.
Here is the problem.
Update panel on asp.net (in this case, SharePoint) page:
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Load" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Lets say in the code behind we add a user control to the placeholder when the button is clicked.
protected void Button1_Click(object sender, EventArgs e)
{
MyControl ctrl = new MyControl();
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(ctrl);
UpdatePanel1.Update();
}
Finally, let's say our user control has some inline scripts.
<script type="text/javascript">
var myInt = 1;
alert(typeof myInt);
</script>
Putting the above together and running it would lead to an update panel that is empty (except the button) by default- get's some data added when the button is clicked that looks like the javascript above. The problem is the javascript code above will never fire.
In my real life case the user control is not terribly complex- it has a repeater that is populated when the control is loaded then some inline javascript which transforms the repeater data a bit. The data comes through but the javascript is never executed and throws no errors.
Attempted solution:
Wrap inline javascript in a function called initMyCode() then use:
ScriptManager.RegisterStartupScript(this, this.getType(), UniqueID, "initMyCode()", true);
...on the user control page load event. This fails as initMyCode() cannot be found within the page.
Anyone have a workable solution for this issue?
if(!Page.ClientScript.IsStartupScriptRegistered("initMyCode")){
string script =#"function initMyCode(){var myInt = 1;
alert(typeof myInt);}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initMyCode);"
ScriptManager.RegisterStartupScript(this, this.getType(), initMyCode, script, true);
}
Or
<script type="text/javascript">
function initMyCode(){
var myInt = 1;
alert(typeof myInt);}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initMyCode);
</script>
Have you already tried adding your code in the "ready" of jQuery?

How do you output raw javascript in asp.net

I would like to output raw javascript to an aspx response. Using response.write fails because along with the javascript, it dumps all of the other asp.net stuff in the page, for example:
...
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTAxODk4MjA3OWRk9jVlI2KaQPiVjEC+P0OPYGV74vKjJQZuwD6OaHhb+U0=" />
...
Is there anyway to simply output raw text to the output without having all of the other asp.net stuff on the page? I am trying to use the page as follows:
<script src="mypage.aspx"></script>
Where this page contains the javascript this triggers off the aspx page, however chrome doesn't like it for obvious reasons... it expects javascript, but it is getting javascript + markup + .NET injected stuff.
Please no comments on why I am doing this! Working on very specific problem.
Use .ashx Generic Handler. Then you can set context.Response.ContentType = "text/javascript" and just use Response.Write
I'm not sure that I understand your question, but you can try something like this:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "registerSomething", "doSomething = function(){ ... }", true);
You could also disable the viewstate, etc... and remove everything from the aspx file.
<%#Page ... EnableViewState="false" EnableViewStateMac="false"%>
Include nothing else in the aspx file, no runat=server anything. Then write your javascript in the codebehind using response.write.
This will be pretty tough using WebForms. The best way I can think of would be to add MVC to your project so you can have more control over the output. (Yes, MVC and WebForms can coexist in the same project).
This way you can still leverage the .aspx syntax (or the even-cooler Razor syntax) to produce a javascript file, without WebForms adding all of its annoying stuff to your output.
I needed this and this was my solution:
Created a file script.aspx and the content was straight javascript with the header directive of the page. Then in the javascript I was able to insert calls to static methods:
<%# Page Language="C#" ContentType="text/javascript" %>
function someFunction()
{
var someVar;
someVar="<%= MyClass.MyMethod() %>";
}
That returned just pure javascript with the server side insertions as needed:
function someFunction()
{
var someVar;
someVar="Some string returned by my method";
}

Once again, how do I convert ct100 IDs to original id using javascript?

I have a tag element in .aspx page:
<a id="loginLink" runat="server" class="loginLink" href="#" onclick="$('registerform').hide(); $('signin').show(); this.style.display='none'; $('back').show(); $('reg-signin-email').focus(); return false">Already signed up? Log in here</a>
and trying to get loginLink.ClientID , but it spits back ct100_main_loginLink. How do I get original 'loginLink' id in the same aspx page?
Tried var ctrl = document.getElementById('<%# loginLink.ClientID %>');
and it didnt work..
example:
<asp:Content runat="server" ContentPlaceHolderID="Main">
<a id="loginLink" runat="server" class="loginLink" href="#" onclick="$('registerform').hide(); $('signin').show(); this.style.display='none'; $('back').show(); $('reg-signin-email').focus(); return false">Already signed up? Log in here</a>
<script type="text/javascript"> alert('diplay here original loginLink ID instead of ct100_Main_LoginLink'); </script>
</asp:Content>
if you know the name, and that's what you want to have available in js, you can just type it in js. alternatively, if you want the control to provide its own id, you could do
<script type="text/javascript">
alert('<% =loginLink.ID %>');
</script>
although I don't see the point in that. if you need to grab the element during a javascript routine, you'll need the ClientID value as there won't be any element on the page with the short-form id in the example I've given.
You need to write '<%# loginLink.ClientID %>', and you can only write it in the original ASPX page. (Not an external JS file)
If you wnat to get the original ID (which never shows up on the client), use loginLink.ID.
if you use a tool like FireBug you will see that the actual ID output to the client is the long one with ct100.... in ASP.NET pages.
You will not normally get loginlink back to the client unless you are using Dot.NET 4.0 and controlling the client-mode.
in your example the var ctrl should hold a reference to the DOM element

Categories

Resources