I want to make this code work on c# code behind. I know in C something similar can be done, but can it be done here?
protected void Page_Load(object sender, EventArgs e)
{
Bar.Text = "Updating Information";
InsertData();
Bar.Text = "Information Updated";
}
protected void InsertData(object sender, EventArgs e)
{
//loops and statements
}
any ideas?
Two things. First, you're not passing the expected parameters:
protected void Page_Load(object sender, EventArgs e)
{
Bar.Text = "Updating Information";
InsertData(sender, e);
Bar.Text = "Information Updated";
}
protected void InsertData(object sender, EventArgs e)
{
//loops and statements
}
Second, this looks like ASP.NET Web Forms. The changes to the Text property of your control will not update the UI. To understand why, you have to understand what's really going on outside the bounds of the actual code you write. ASP.NET WebForms have a very high degree of "inversion of control"; your code lives to serve the ASP engine resident in the IIS webserver, and has very little ultimate control over when it runs (or even when it exists).
This has two major consequences for you; first, the amount of state information retained by the server about each client asking for pages from it is very low; ideally, no state is saved (but realistically the server must usually keep track of some "session state", especially for secured web apps requiring a login). In fact, your codebehind class only lives as long as it takes to render a page; after that, the class (and any state data it was trying to store in memory) are disposed of and garbage-collected.
Second, and more importantly for you, anything done in the codebehind to render the next requested page will not result in real-time updates for the client; everything your code does in the codebehind, from Page_Load to Page_OnPreRender, is performed before a single bit of the resulting HTML is sent back to the client. The upshot is that changing the value of a control on the form several times during the execution of codebehind event handlers has zero bearing on what the client sees, unless you specifically set up additional communication with the client. The updating of Bar.Text before calling InsertData() will not cause the client to see the message "Updating Information". All the client will ever see is "Information Updated", because that is the text of the control as of when the page is finally rendered into HTML, after all your event handlers execute.
Problems like these are typically resolved with asynchronous architectures such as AJAX (Asynchronous Javascript And XML). JavaScript's level of control over the rendered page in the browser window rivals that of a WinForms application (enough that you can program simple games with HTML as your UI using only client-side JavaScript), and there are methods and objects JavaScript can use to send requests for data to your server. So, to keep the user's displayed page responsive during this insert operation, you could employ these tricks. You'd have a button on your page that, instead of triggering a full postback of the entire page, would instead trigger a Javascript method on the client that would send a web service request to your server, and also update the value of your Bar UI control text with the status "Updating Information". The server would perform an action (your "InsertData()" call) and then respond to the client's browser, which would trigger a second JavaScript method that would update the status again with "Information Updated".
As an aside, it is in fact possible to create entire web applications using this Javascript-based "service-oriented architecture" for all content updates, where only one initial HTML page is ever served to the client browser, and all further changes to that page's layout, content and behavior is controlled by JavaScript updating the one page's DOM based on data received from web service calls. Such architecture of a website has its downsides, but also some big advantages.
Bar.Text = "Updating Information";
InsertData(this, EventArgs.Empty);
Bar.Text = "Information Updated";
You can change your InsertData() method, since you are calling it with no parameters.
protected void InsertData()
{
//loops and statements
}
Do you need to know the sender or pass EventArgs? You could simple redefine the InsertData Method as
protected void InsertData()
{
//loops and statements
}
and then call the method via
Bar.Text = "Updating Information";
InsertData();
Bar.Text = "Information Updated";
Related
I'm doing a project for school and i have this page with some search results.
When i go back to the search results page, the browser asks to "Confirm Form Re-submission" and i would like to avoid this.
I haven't done nothing so far to solve this issue besides searching the web for a solution and not had not found one.
Browser message:
Confirm Form Re-submission
This web page requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed.
Press the reload button to resubmit the data needed to load the page.
ERR_CACHE_MISS
The problem lies in that you are doing a post request, and if the person making use of your web page refreshes it, it does what it is supposed to do resubmit the post request.
Hence, there is no way of preventing this issue from happening, what you could rather do is changing the way you obtain the values from a post request to get request.
Hi. Found the solution for my problem.
So what i did was, stored the value in session, redirect to a loop page and back, and just preform the search on form load. Now i can go back and forth with no problem. Here is the code i used:
Search page:
protected void btnSearch_Click(object sender, EventArgs e)
{
Session["searchValue"] = txtSearchValue.Text;
Response.Redirect("loopPage.aspx");
}
Code on LoopPage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("searchPage.aspx");
}
search page again:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["searchValue"] != null)
{
...preform search and create objects to present results...
}
}
I have a c# asp.net page and an update function which will update the database. In this function I would like to call some client side javascript. I've read a lot about registering a start up script in page_load() but this is always trigger on page load (funny that!)
How would I register then call a script inside my update function? Triggered when a user clicks the "update" button. I have tried the following (inside my function)
protected void doUpdate(object sender, EventArgs e) {
string jScript;
jScript = "<script type=text/javascript>alert('hello');<" + "/script>";
ClientScript.RegisterStartupScript(GetType(), "Javascript", jScript);
}
but it isn't fired. Any ideas? Many thanks.
[update]
It's now working - the function looks like this
protected void doUpdate(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(),"Javascript", "cleanup();",true);
}
Cleanup() is the javascript function in my HTML. Thanks for the help guys :)
If the control causing the postback is inside an UpdatePanel you need to use
ScriptManager.RegisterStartupScript
You can't 'execute' client side scripts from the web server (the client knows who the server is, but not the other way around).
The only way to overcome this limitation is by a. create a long-polling process that requests something from the server, the server doesn't complete the request till it has something to return (then client side it makes another request).
What you are really looking for is websocket (duplex) enabled communication. You can check out alchemy websockets or SignalR (has a pretty nice library with dynamic proxy generation).
The reason why that 'script always works on Page_Load' is because it effectively injects your script tag into the html returned for the page requested.
Your Update button is likely using the standard ASP Button behavior, meaning it is type="submit" when it is rendered. Since that's the case, you can just use:
Page.ClientScript.RegisterOnSubmitStatement
Keep in mind that will register a script for every postback, not just the Update button. So, if you only want some javascript run on clicking Update, you would need to check if the EventTarget is UpdateButton.ClientID. Also, RegisterOnSubmitStatement always adds the <script> tags, so don't include those in the javascript statement.
An even easier solution, the ASP Button itself also has an OnClientClick property. This will run client-side code (javascript) when the button is clicked in the browser.
I want the server to desplay some text on a webpage.
I defined
<asp:Label id="label1" runat="server" />
and set
protected void Button1_Click(object sender, EventArgs e)
{
label1.Text = "bla";
timer = new System.Threading.Timer(new TimerCallback(DoSomething), null, 0, 10000);
}
private void DoSomething(object obj)
{
label1.Text = "bla 1";
}
bla is presented, but not bla1.
When I debug I see the "bla 1" line is executed.
Where do I do wrong?
By the time DoSomething() gets executed, the response has already been sent to the browser, and your code does nothing. Actually, I'm surprised you don't crash the app domain with it.
You should not attempt to use threading primitives like this in an asp.net application.
If you want to update the value sometime "later" than the initial page displaying, you'll need to look at Ajax.
I would think that the new timer doesn't complete before the page response is sent. The thread is probably throwing an error and just shutting down.
You can't asynchronously change a label in another thread like that, once the response is sent back to the browser then nothing you do on the server will make any difference. You will need to do client side ujpdates using javascript.
ASP.Net runs the code on the server and spits the result back to the browser, once this is completed nothing that happens on the server will have any affect on the html in the browser.
The reason is when you click the button the request/response process occurs.
Your thread is not refreshing the page or its fragment in any way.
Possibly you can achieve required result with websockets or ajax long pooling - with comet.
I have a custom dll loaded into my web application, I updated it and reloaded the reference in my main web app. Basically the way it works is a user uploads a file that gets checked by a function in the dll. The user can then click a button on the results section that redirects to the main section of the app so they have a choice of rerunning the checker; I say section because the web app uses a single page with two divs, one for the form and one for the results, the code behind then swaps the visibility of the form div from the results div, here's the basic layout to clarify.
<body>
<div id="divForm" style="visibility: visible;">
</div>
<div id="divResults">
</div>
</body>
The redirect call is in the code behind as follows:
protected void btnReturn_Click(object sender, EventArgs e)
{
Response.Redirect("http://localhost/file_checker/");
}
And the main piece of the file checker:
protected void Page_Load(object sender, EventArgs e)
{
divForm.Visible = true;
divResults.Visible = false;
if (Page.IsPostBack)
{
//Do file checking
//Show results
divResults.Visible = true;
divForm.Visible = false;
}
}
The web app works fine on the first pass, however, I notice strange behavior after every subsequent pass. For example, I notice that the results page shows stale content from an older version of dll, i.e. It displays a string that was generated by an older version of the dll, I had removed the string and yet it still gets generated. I'm not sure if I'm redirecting correctly or if there's some other fundamental misunderstanding I have with how redirects work. Any help or insight is appreciated.
UPDATE:
Ok, instead of redirecting, I just cleared a gridview in my results section and swapped the styles of the divs to show the main section and hide the results section as follows:
protected void btnReturn_Click(object sender, EventArgs e)
{
//Clear the Gridview and show the upload Form
GridView1.DataSource = null; //<--Is popoulated by a DataTable
divForm.Visible = true;
divResults.Visible = false;
//Response.Redirect("http://localhost/file_checker/");
}
That seems to fix the problem, a lingering question I have is, I'm using a Datatable to populate the Gridview in the results page. Does the Datatable automatically dispose itself after each page load or button click event? Or will it persist? I just want to avoid any memory leak issues, since each page load instantiates a new DataTable object.
A Response.Redirect sends a 302 response to the browser. The browser then makes a new request to the new location. So it isn't a server side operation, and the browser can cache the response and not make the call again. Try appending a querystring parameter to make the browser do a true request. If you have fiddler available, you might use that to verify, but you are probably getting the page from cache.
protected void btnReturn_Click(object sender, EventArgs e)
{
Response.Redirect(String.Format("http://localhost/file_checker/?{0}", DateTime.Now.Ticks));
}
I don't know alot about ASP.Net but I'm trying to make a new control for a message box. You enter some info and press a button.
However, for some bizarre reason when the button is pressed, Page_Load() gets called a second time, and all of the member variables are reset to null! I need those variables, and Page_Load() has not reason to be called a second time! Of course the callstack is useless.
Remember, in ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is gone. That means running the entire page life cycle, including your page load code, and not just the click code.
Always two there are, no more, no less. A request and a response.
When the page posts back, the Page_Load method is called. Then, once the server actually processes the page and sends you a new one based on changes, the Page_Load is called again, actually the first time on the new page sent to you.
So if you are pulling data in the Page_Load event or setting some values, enclose it in the following block:
if(!Page.IsPostBack)
{
}
to preserve some of your state. Otherwise, the instructions that you put into the Page_Load event will execute every time.
It helps to review the ASP.Net page lifecycle :)
As Joel mentioned, instance variables will be lost once the page is sent back to the client. However, there are various methods of storing the values of your variables so you can retrieve them later. This page on State Management is a good starting point if you want to learn more.
Any tag/element which requires url reference like img, anchor, object etc must be checked for the empty reference.
e.g. href="", url="", src="" are some common errors.
This code works for me:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["something"] == null)
{
Session["something"] = "1";
}
else
{
Session["something"] = null;
//your page load code here
}
}
}
For me, the issue was a bit complicated, but I found that the
protected override void OnPreRender(EventArgs e)
handler is only called once, so it's safer to put some actions in there if it's not too late in the pipeline for you.
An extension of #user3207728's response, I found this link explains it well and has a simple solution...
http://www.aspdotnet-suresh.com/2010/04/detect-browser-refresh-to-avoid-events.html
Unfortunately checking just for if (!Page.IsPostBack) is not enough as IsPostBack will always be FALSE on a refresh.
Just a shot in the dark but maybe add this after your page_load:
if (!IsPostBack)
{
you can use sessions or viewstate to retain the values of variables..
if you want to redirect to a different page , use session[]
else if you want to stay on the same page , use viewstate[]
In my Case the Problem Was Related to Iframe, One Time I removed the Iframe Everithing Work Fine
<iframe id="pdf2"
src="#"
width="100%"
height="100%">
</iframe>