I used the below manner to run a JavaScript upon postback and it worked fine for me.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'hidden';</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>function show()</script>");
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'visible';</script>");
}
}
The above code worked fine and now I want to try something like below.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"verify","<script type='text/javascript'>verify1();</script>");
}
else
{
}
}
in the above code verify1() is a JavaScript linked externally to ASPX page. I am unable to execute verify1() function using this code. And verify1() function works fine when placed as <body onload="verify1();"> Is there any syntax error(s) in my above code?
this may help you,
Page.ClientScript.RegisterStartupScript(this.GetType(), "verify", "verify1()", true);
Maybe that script is being executed before verify1()'s function definition. By the time body.onload fires, the main page has completed parsing and all external scripts have been loaded, which is why it works in that scenario.
Can you use jquery? One option is to use jQuery's onload functionality, which won't be executed until everything is intialized:
$( function() { ...my startup code... });
Related
Clarification: I am chilean, so my english is not perfect, sorry for the misspellings.
Hi, I am working with an image in c#.
I try to put an example image when the page open the first time, I used the post back for this, but when I press a button, execute the code in the post back section (which is right), after that it execute the Button code, but then, it pass again for the Page_Load method, and execute the "not post back" section, and i dont know why.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//Is post back
}
else // Is not post back
{
//Make things only when the page is open for the first time
}
}
I usually only use (!IsPostBack) on PageLoad for doing initial data loads or validations(like settings for users).
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (userIsAdmin)
{
button1.Enabled = true;
}
}
}
You could refer to the link for the explanation for PostBack https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.ispostback?view=netframework-4.8
I'm trying to get the height/width of an image using JQuery.
It won't work until the image is fully loaded by using $(window).load.
When doing an asp.net UpdatePanel, the events are unbind from the elements. I've tried using ScriptManager.RegisterStartupScript to call a Javascript function to bind all of the events again, but it won't run the $(window).load. Please help.
External JS Code
$(window).load(function () {
WindowLoad();
});
function WindowLoad() {
alert($("#test").width());
}
C# Code
protected void Page_PreRender(object sender, EventArgs e)
{
if (IsPostBack)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "WindowLoad" + DateTime.Now.Ticks, "WindowLoad();", true);
}
}
protected void Previous_Click(Object sender, ImageMapEventArgs e)
{
String value = e.PostBackValue;
if (value == "test")
{
imgTest.ImageUrl = IMAGEPATH;
}
}
When the page first loads. The $(window).load gets the height/width of the image just fine because it waits for the image to finish loading onto the page before it displays the width/height.
When you click on the imagepath, it'll do a partial postback. When that occurs, the JS are unbind from the elements. Previous_Click will run first and then the Page_PreRender to register the JS on the elements. This is where I need to make sure I get the height/width of the image again. So that JS can do some recalculations. On the partial postback, the results ends up being 0. I do notice that the UpdatePanel takes a while to update the image path, so they may have some cause as to why the results become 0, but I would assume the UpdatePanel will finish loading everything first before trying to run the WindowLoad function.
Having just added a new button in my web application, I get an error when clicking on it, and I'm wondering if this is related to misplaced code. I will describe what/where I did, briefly. Thanks very much.
In ascx file:
<asp:Button ID="btn_rezerv" runat="server" Text="Reserve film" OnClick="btn_rezerv_Click"/>
In the ascx.cs file:
namespace CinProj.UserControls
{
public partial class FilmsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string categId = Request.QueryString["CategID"];
string filmId = Request.QueryString["FilmID"];
....
if (categId != null)
{
.....
}
if (filmId != null)
{
......
Button btn_rezerv = (Button)item.FindControl("btn_rezerv");
}
}
protected void btn_rezerv_Click(object sender, EventArgs e)
{
string fid = Request.QueryString["FilmID"];
ShoppingCartAccess.AddItem(fid);
}
}
}
"Server Error in '/' Application.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "
Another problem could be because your PopulateControls method should probably only be called when during the Page Load when it's not a PostBack. I can't tell from above, but to me it looks like it only needs done on Load. Try wrapping that call with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateControls();
}
}
It's likely the result of making some sort of client change that the server doesn't know about. Many times this is the result of changing values in a dropdown in JavaScript, for example.
To fix, you could:
Do away with using JavaScript for said modification
Use an UpdatePanel and add your control to it. If the client needs to make a change, trigger the UpdatePanel's update in order for the control's viewstate to update.
I'm gonna post some more code to show exactly what I'm trying to do,
I'm adding the button using programming code and not markup but the OnClick won't work (giving the following error:
System.Web.UI.WebControls.Button.OnClick(System.EventArgs)' is inaccessible due to its protection level.
Button btnopslaan = new Button();
btnopslaan.Text = "Opslaan";
btnopslaan.ID = "btnOpslaan";
btnopslaan.CssClass = ".opslaan";
btnopslaan.Click += new EventHandler(btnopslaanClick);
btnopslaan_arr[btn_count] = btnopslaan;
add_button(btnopslaan);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("success");
}
I just can't find out why this isn't working.
Anyone who can help me out?
You need to use OnClick for server side clicks rather than OnClientClick
Either you can use it inline >
<asp:Button id="btnopslaan" runat="server' OnClick="btnopslaanClick" />
Or in Code behind >
btnopslaan.Click+=new EventHandler(btnopslaanClick);
or you make it a postback call to the server. in your
aspx write:
<asp:Button runat="server" ID="buttonOpslaan" Text="opslaan" ></asp:Button>
codebehind write this:
protected void Page_Init(object sender, EventArgs e)
{
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
}
// mind: this method can be private
void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it with the AutoEventWireUp (recommended) like:
<asp:Button runat="server"
ID="buttonOpslaan"
OnClick="buttonOpslaan_Click"
Text="opslaan" ></asp:Button>
// mind: this method cannot be private, but has to be protected at least.
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or do it completely from code behind:
// note: buttonOpslaan must have an (autoassigned) ID.
protected void Page_Init(object sender, EventArgs e)
{
Button buttonOpslaan = new Button();
buttonOpslaan.Text = "opslaan!";
buttonOpslaan.Click += new EventHandler(buttonOpslaan_Click);
form1.Controls.Add(buttonOpslaan);
}
protected void buttonOpslaan_Click(object sender, EventArgs e)
{
//do something
}
or handle it clientside with javascript in your ASPX (it will not reach the server)
<script type="text/javascript">
function buttonOpslaan_Click(){
alert("test");
return false;
}
</script>
<asp:Button runat="server"
ID="buttonOpslaan"
OnClientClick="buttonOpslaan_Click()"
Text="opslaan" ></asp:Button>
Update: (by comments)
if you add the control via an eventhandler (like the onchange event of a dropdownlist), the control is 'lost' on next postback, or even as soon as the Page is send to the client (due to the stateless (there is no mechanism to maintain the state of application) behaviour and lifecycle of .Net).
So simply adding a control once is never going to work.
That means you have to rebuild the control every time a postback occurs. My preferred way to do this is store a list/document somewhere that descrbes what controls must be created each time. Possible locations are, from worse to good (IMHO):
Session
Viewstate
Cache
XML/IO
Database
After all, you are posting "data" to the server (that represents a control) and you want to save that for further use.
If the controls to be created aren't that complex you could implement a Factory Pattern like a WebControlFactory that stores only a few properties in a List or Dictionary, which is read every time to recreate the controls again (and again, and again, and again)
btnopslaanClick should be client side, in the .aspx itself have:
<script type="text/javascript">
function btnopslaanClick() {
alert("success");
}
</script>
btnopslaan.Click+=new EventHandler(btnopslaanClick);
protected void btnopslaanClick(object sender, EventArgs e)
{
Debug.WriteLine("succes");
}
I have a button on my aspx page. I want to use javascript confirm before continuing execution when clicking on that button. I can do it easily if i am writing javascript in aspx page itself . But my problem is each time the confirm message may be different. I need to check various condition to generate appropriate confirm message.
Can I call confirm in my code behind, so that I can construct confirm message from there?
What I'm trying is:
protected void Button1_Click(object sender, EventArgs e)
{
//just the algorithm given here
string message=constructMessage(); \\ its just a function to construct the confirm message
if(confirm(message)) // i know i cant use javascript in code behind direct. How can i do this
{
//do something
}
else
{
// do nothing
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string message=
"if(confirm("+message+"))
{
//do something
}
else
{
// do nothing
}";
this.ClientScriptManager.RegisterStartupScript(typeof(this.Page), "warning", message, true);
//Prints out your client script with <script> tags
}
For further reference on ClientScriptManager
I just got this link which describes different ways of calling javascript
http://www.codedigest.com/Articles/ASPNET/314_Multiple_Ways_to_Call_Javascript_Function_from_CodeBehind_in_ASPNet.aspx
may be this will help..