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?
Related
I want to pass data from back-end to front-end and front-end to back-end so far I have tried like below
back-end to front-end :-
back-end (.aspx.cs):-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
}
front-end (.aspx):-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert(amt); // data coming
</script>
</form>
</body>
The above example is working fine but while passing the value from front-end to back-end I'm getting the null("") value (for this concept I have read this article)
front-end to back-end :-
front-end (.aspx) :-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert("amt :- " + amt);
function getval() {
var keyid = "1234";
document.getElementById('key_id').value = keyid;
alert(document.getElementById('key_id').value);
alert('hit');
window.location.href = "http://localhost:49855/ValuePassig.aspx";
}
//alert(amt);
</script>
<input id="key_id" runat="server" type="hidden" name="key_id_1" />
<input type="button" id="btn" value="click" runat="server" onclick="getval()" />
</form>
</body>
back-end(.aspx.cs) :-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
//I'm getting the null("") value
//string kId = this.Request["key_id_1"];
//string kId = Request.Form["key_id_1"];
string kId = key_id.Value; //Initially the value come null(acceptable) and next I'm clicking on the "click" button at that time null value should not come(but coming)
Response.Write(kId);
}
I did my best so far to achieve this concept and I don't why I'm getting a null value because, I have followed the article also(above mentioned link) to achieve this
concept
Suggest me where I did the mistake to pass the value from front-end to back-end and how to achieve this
Please give me your best suggestions.
Note :- I have changed the code for better understanding that is button added and when I click on the button the hidden value should come back-end.
Ok, so we want to have some value - set in code behind cs, to set/pass/have some value for use in the client side js code.
And of course in the js code, we want use of that value, and ALSO to be able to change that value, and then upon actions, or code behind, we want that value passed back to the code behind.
First up, don't use a server side expression to "set" that value for use in the js code. The reason of course then you don't have a easy way to pass back and have use of that change value in the code behind.
You can freely change the var in js code, but you really don't have a easy/nice way to get that value back to the code behind (so that <%= %> expression is a one way street to the client side.
There are a LOT of ways to do this, but probably best is to drop in a hidden field control (as per your question title)..
You can also use a hidden text box, but might as well use the hidden field.
So, lets on page load (and ONLY first page load - like all setup on the page should be inside of the !IsPostBack code block - all web pages quite much need this !IsPostBack code block).
And bonus?
the Hidden field control has automatic view state. (that means the value will persist on page post-backs).
So, lets drop in a server side button to "show" the value.
And THEN lets drop in a button (client side) to show the value, and ALSO to modify the value.
<asp:HiddenField ID="MyHotelName" runat="server" ClientIDMode="Static" />
<h3>Server side code</h3>
<asp:Button ID="cmdShowServer" runat="server" OnClick="cmdShowServer_Click"
Text="Show Hotel Name" CssClass="btn" />
<br />
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<h3>Client side code</h3>
<asp:Button ID="cmdShowClient" runat="server" Text="Show Hotel Name"
OnClientClick="ShowHotel();return false" />
<br />
<asp:Button ID="cmdChangeClient" runat="server" Text="Change Hotel Name"
OnClientClick="ChangeHotel();return false" />
<script>
function ShowHotel() {
alert("Hotel name = " + $("#MyHotelName").val())
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
$("#MyHotelName").val(sHotelNew)
}
</script>
And our code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyHotelName.Value = "Zoo";
}
}
protected void cmdShowServer_Click(object sender, EventArgs e)
{
lblShow.Text = "Value of hotel = " + MyHotelName.Value;
}
So, we now have this:
Edit: Above used jquery.
Of course the js code above used jQuery.
however, we could assume pure js code, no jQuery.
so, the js code would then become this:
<script>
function ShowHotel() {
sHotel = document.getElementById("MyHotelName").value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById("MyHotelName").value = sHotelNew
}
</script>
I should also point out the "very" imprortant adding of clientidmode="static" for the hidden field. This will "prevent" asp.net system from changing the "id" used for the control, and as a result, the js code tends to be more "clean" and "easy" to reference controls.
If you don't want to use clientidmode=static for the hidden field, then the above code then becomes this:
hidden field thus is this: (no client id mode).
<asp:HiddenField ID="MyHotelName" runat="server" />
And now our code becomes this:
<script>
function ShowHotel() {
sHotel = document.getElementById('<%= MyHotelName.ClientID %>').value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById('<%= MyHotelName.ClientID %>').value = sHotelNew
}
</script>
So, I often will toss in a ClientIDMode="static" for the hidden field, as that makes the js code to get the hidden control less messy.
I want to execute a RegisterStartupScript calling a Javascript function after certain processes happen in my code behind. It is basically a Loading loop decoration made in CSS3. I show it (with javascript) on buttons clientclick, when I know the process will take a while and I hide it when the process is finished. Everything works fine, but now I have a process in Which I download a file using another empty webform using response.redirect. The file is downloaded fine, but the RegisterStartupScript call does not work. I understand the response is the problem, but nor I need to work in a workaround to solve this (I do not want to change the whole way, cause it is implemented in many other pages and processes. I wil provide the related code (not all), in case you can give me a direct way to solve it.
Javascript
function LoadingLoopOn()
{
$('#outerAlignId').addClass("outerAlign");
$('#middleAlignId').addClass("middleAlign");
$('#innerAlignId').addClass("innerAlign");
$('#OutterCircleId').addClass("OutterCircle");
$('#InnerCircleId').addClass("InnerCircle");
$('#Loadinglbl').addClass("LoadingLabelStyle");
}
function LoadingLoopOff()
{
$('#outerAlignId').removeClass("outerAlign");
$('#middleAlignId').removeClass("middleAlign");
$('#innerAlignId').removeClass("innerAlign");
$('#OutterCircleId').removeClass("OutterCircle");
$('#InnerCircleId').removeClass("InnerCircle");
$('#Loadinglbl').removeClass("LoadingLabelStyle");
}
HTML (it is on the master page, to be able to used it in every webform)
<asp:Panel ID="outerAlignId" ClientIDMode="Static" runat="server" CssClass="outerAlign">
<div id="middleAlignId" class="middleAlign">
<div id="innerAlignId" class="innerAlign">
<div id="OutterCircleId" class="OutterCircle"></div>
<div id="InnerCircleId" class="InnerCircle"></div>
<asp:Label ID="Loadinglbl" ClientIDMode="Static" runat="server" Text="Loading..." CssClass="LoadingLabelStyle"></asp:Label>
</div>
</div>
</asp:Panel>
HTML Button Sample Where I want to used it
<asp:ImageButton ID="ExportExId" ClientIDMode="Static" runat="server" OnClientClick="LoadingLoopOn();" OnClick="ExportExId_Click" CssClass="..." ImageUrl="..." />
And the CS# Code behind
protected void ExportExId_Click(object sender, ImageClickEventArgs e)
{
//...
//Many code and DB treatment goes here, to finally get a temporally Excel file in the server
//..
//I call the page with the file name and path
Response.Redirect(String.Format("DownloadForm.aspx?FileName={0}&Path={1}", fileExported.Name, "Temp" + UserName));
//This piece of code must be excuted in its webform after the redirect (once ee finished)
ScriptManager.RegisterStartupScript(this, GetType(), "LoadingLoopOff", "LoadingLoopOff();", true);
}
As I marked in my comment, A possible solution could be AJAX. Make an ajax call to force a page update and then the function would be processed (on the load), or directly call the function through this ajax call. The problem is that I do not know how to uise AJAX in this case...
Many thanks,
strScriptString = "alert('Hello');";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Startup", strScriptString, true);
btn_Click(this, null);
The alert is not showing up :(
please help
You need to still put the script tags around your alert:
strScriptString = "<script>alert('Hello');</script>";
EDIT
My mistake, read the wrong RegisterStartupScript class
Have you checked the source of the page for the script using Firebug? I'll hazard a guess that if you remove btn_Click(this, null); it may work.
You can add following code snippet into page_Load..
btnUpdate.Attributes.Add("onclick", "GetAlert();");
Button Click event in code behind.
protected void btnUpdate_Click(object sender, EventArgs e)
{
btnUpdate.Text = "Reload";
}
Button in aspx page
<asp:Button ID="btnUpdate" runat="server" Text="Submit" OnClick="btnUpdate_Click"/>
Javascript for alert
<script>
function GetAlert() {
alert("123");
return true;
}
</script>
If you're looking to show an alert before the server-side event fires, use OnClientClick, and return true.
<asp:Button ID="Button1" runat="server" OnClientClick="alert('Hi!');return true;" ... />
How do I fire a server side button click event from JavaScript?
I tried like this:
document.getElementById("<%= ButtonID.ClientID %>").click();
But no use. How can I do it?
You can just place this line in a JavaScript function:
__doPostBack('btnSubmit','OnClick');
Or do something like this:
$('#btnSubmit').trigger('click');
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
None of the solutions posted here would work for me, this was my eventual solution to the problem.
// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
Page.GetPostBackEventReference(hiddenButton);
}
// Javascript
function SetSaved() {
__doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}
// ASP
<asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>
I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...
I mean ->
I have an html submit button and an asp button like these:
<input type="submit" value="Siparişi Gönder" onclick="SendEmail()" />
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
SendToEmail() is a server side method in Default.aspx
SendEmail() is a javascript method like this:
<script type="text/javascript" lang="javascript">
function SendEmail() {
document.getElementById('<%= sendEmailButton.UniqueID %>').click();
alert("Your message is sending...");
}
</script>
And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.
Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.
Then suddenly I changed html submit button --> just html button like this and now it is working:
<input type="button" value="Siparişi Gönder" onclick="SendEmail()" />
Have a nice days...
I can make things work this way:
inside javascript junction that is executed by the html button:
document.getElementById("<%= Button2.ClientID %>").click();
ASP button inside div:
<div id="submitBtn" style="display: none;">
<asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>
Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
cmd2.CommandText = insertSuperRoster;
cmd2.Connection = con;
cmd2.ExecuteNonQuery();
string url = "VaccineRefusal.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
}
Any ideas why these lines won't execute?
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
document.FormName.btnSubmit.click();
works for me. Enjoy.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
The issue I had was the validation group that was not specified.
I added ValidationGroup="none" as per below and it worked.
<asp:Button ID="BtnQuickSearch" runat="server" Text="Search"
OnClick="BtnQuickSearch_Click" ValidationGroup="none" />
I must mention that I had 2 other forms with buttons on the page, both had their own validation groups specified. This button had did not have a validation group specified and the onclick event simply did not fire.
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%>';