I am attempting to persist what the users enters into a textbox without them clicking save. It would simply save what the user entered into the textbox so when they navigate away and then back to the page it will be reloaded. once they are click "done" the session will be removed.
I have been trying to do this with Jquery but I have been struggling as I am fairly new to JavaScript, can anyone point me in the right direction?
You can use the onChange event of the textbox to call your save routine everytime the user changes the text; alternatively you can run a saving function every while using the setTimeout javascript function. Like RaYell said, you can store your values inside a cookie. If you use JQuery, you can take advantage from http://plugins.jquery.com/project/Cookie which offers super simple ways to read and write cookies.
You can use a cookie to store textbox value. A nice tutorial how to use cookies is here
Related
I am trying to implement a like counter. That on a click of button increases like count by one in the database and then I am changing its text to "unlike" after clicking again my value is decrementing by 1 in the database too. It all works fine untill the page is posted back.
For eg. If a user clicks like button then text of that button changes to unlike. But if the user reloads the page then. He again gets the button as "like" but not "unlike" is there anyway I can save the state even after postback in asp.net.
Thanks in advance.
You will need to store the 'like' state in a session variable if you want it available between page switches/reloads.
This might help:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/e43755ba-49f1-49b9-aa68-448ecf033a62/how-do-you-store-session-variable-in-c?forum=csharpgeneral
Alternatively, get the 'like' state from the database when generating the page.
If you're still experiencing issues, your browser might be caching the page.
If you are on to Javascript, you can try SessionStorage to hold values between page refreshes. It lasts only within the lifetime of a browsers tab and automatically destroyed when the tab/ browser is closed. Values remain completely on the client side and managed by the browser.
Session Storage (W3Schools)
Ex (extracted from the above website):
// Store
sessionStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = sessionStorage.getItem("lastname");
I need to add possibility to changing menus from old design to new. The changes are only the structure of the menu. I don't have any problem with that.
How I implemented the change add button, on button client click(no postback) I made one of the menu divs display:none and set hidden field to 0 or 1. On every post back I read the hidden field value and set the correct div.
My question is: Is it possible to be done without hidden field and to set the choice of the user, so when he log in again to stay with last configuration(not the default). I don't want to use postback, if it possible provide example. Thanks !
You are using JQuery so here it goes. Call the changeMenu() function in $(document).ready to make sure the old is shown first.
var current=1;//old system
//this function will be called in the button click
function changeMenu(){
if(current==0){
$("#oldMenuDiv").hide();
$("#newMenuDiv").show();
current=1;
}else{
$("#oldMenuDiv").show();
$("#newMenuDiv").hide();
current=0;
}
}
I have a session variable that I am using on a page. I know that sessions should be used for the purpose
of storing data between different pages of a website, but I have a big dataset to store and I am using a session instead of a view state.
I would like to empty the session when I navigate to another page.
Is there a way I can do it ?
I tried setting the session variable to null on the PageUnload event, but thats not what I want.
I would like to set the session variable to null while the page is navigated to another page.
Please let me know.
You just need to call
Session.remove("nameOfSessionVariable") ;
And regarding to how to handle the "leaving page event"
You will have to write some front-end javascript to do this using
something like window.onbeforeunload(). Then you'd have to make an
AJAX call to tell your back-end that this event is happening. This
isn't foolproof, of course. A browser crash or a forced "quit" would
not fire this event.
As can be seen here C# ASP.NET Page Leaving event?
If you truly want to detect when user leaves the page - you have to do this from the client-side. Handle onbeforeunload event and make an AJAX call to clear session variable.
But this is an overkill. Consider refactoring the code to store in session smaller amount of data and only that is used between different pages.
On the page you have navigated to you can clear a session variable as follows:
Session.Remove("Name");
To abandon the session completely:
Session.Abandon();
I have an ASP.Net form (Page1) where the user enters some data and then clicks the submit button.
As part of Page1, I have some Validators, including a CustomValidator which needs to do its validation back on the server.
When the user clicks the submit button a post is done to Page1 and the validation routine is run on the server and as long as I check Page.IsValid in the button click routine the form knows whether things have passed or not.
When the validation doesn't pass everything properly goes back to Form1 and the error message is displayed.
When the form does pass validation, I want to pass the data that the user entered to a second form (Page2) so that Page2 can be rendered correctly based on the data the user entered on Page1.
Is there a generally accepted way, or best way, to pass the data to Page2? Here are some ways I know about:
Call Page2 with a query string: This won't work as I need the data to not be visible to the user in certain cases.
Use the PostBackUrl on the submit button to go to Page2: As far as I know, this won't work correctly because then the server side validation routines for Page1 won't be run.
Use Session Variables: I don't know of a particular reason why this would be bad.
Use Server.Transfer: I don't really have any experience with this.
I would think that this would be a pretty standard thing to do but I'm having a hard time finding any information on the correct way to do it.
If you don't have a form of secondary storage for this data, using either Session storage or Server.Transfer would work.
You might find Server.Transfer is a little neater as, this way, you'll retain your POST values across the transfer. This will potentially save you a lot of cumbersome code playing around with session state, which, depending on how complex your forms are, could open the way to all kinds of unusual behaviour that you'd have to predict and plan to deal with in advance such as what happens when a user clicks the "back" button or - if you're posting across multiple pages - what happens when a session expires (plus Servy's examples of having multiple tabs open on the same page(s), all sharing the same session). Working with session state can be messy.
Perform your validation on PostBack then, if Page.IsValid, do:
Server.Transfer("/FormPage2.aspx");
Server.Transfer preserves Request.QueryString and Request.Form, so you can pick up your POST values on FormPage2 and do whatever you need with them here - whether it be using them for conditional logic or rendering them out again as hidden fields to join them up with the values from the second page of the form (bear in mind that if you're doing this you'll have to revalidate the hidden inputs at this stage).
http://msdn.microsoft.com/en-us/library/y4k58xk7.aspx
I have used session state for handling complex forms in the past and found myself wishing I'd used Server.Transfer, which I plan to use for all similar endeavours in the future, unless I have a very good reason not to.
You might also consider using a multiview, but in my experience these can be very messy.
Hope this helps.
I think that the easiest solution would be to specify a PreviousPageType directive. It specifies a type that the page should expect to receive and you would do a normal POST to that page.
On the second page of your application, use the following directive:
<%# PreviousPageType VirtualPath="~/FirstPage.aspx" %>
You will be able to access the properties exposed and check for validity by using something like this:
if (PreviousPage != null && PreviousPage.IsValid)
Using the Session object is a standard way to pass information across forms.
#Servy gives a good explaination (in the comments below) on how Server.Transfer can help you in this case.
The other options you stated all have problems, just like you mentioned...
If you want to use Session:
In the postback of Page1 you can set the values:
Session["myVar"] = <Data you want to pass to page2>
In page2 in the OnLoad:
if (Session["myVar"] != null)
{
myVar = Session["MyVar"]
}
You can achieve this with Server.Transfer by adding a property to your page1. In your second page in page_load for example:
Page1 prev = Page.PreviousPage as Page1;
if (prev != null)
{
// access your property here and set up the page
}
Server.Transfer can safely receive a query string without fear of the user seeing it.
Instead of Session use Context.Items.
Context.Items["validationProblems"] = "...";
Server.Transfer("FixProblems.aspx");
My other comment is that in my experience it's more "standard" to keep the validation UI contained in the same form that's collecting the information. This enables "real time" feedback. In practice I think it's better to give a user information that their doing something wrong as early as possible.
Note, that's just in my experience though.. it's a big world.
It may be more that you presently require, but one alternative is to save the data in a database:
http://msdn.microsoft.com/en-us/library/6tc47t75%28v=VS.100%29.aspx
http://www.asp.net/web-forms/videos/how-do-i/how-do-i-set-up-the-sql-membership-provider
I have a save button which when clicked should make some changes in the database.
if (bFound== false)
{
// Giving the warning message
// If user presses cancel then abort
// Prepare the list of dbId needs to be deleted
deletedBSIds.Add(dbId);
}
Here if the bFound field is true it should not execute the above statement, but if it is false it should go in the condition and then ask if the user want to save changes "yes" or "no".
If the user says yes it should go to the command "deletedBSIds.Add(dbId);" and keep executing further but if the user presses No it should basically abort and do nothing at all.
Is there a way to do this?
Any help would be appreciated.
This is a server side event. so i think cannot add a click event in my button/..
Here the message box only pops up if the bFoung field is false. or else it will not pop up at all.
Please correct me if u feel i am wrong..
thanks
You'll want to add the following to the button:
button.OnClientClick = "return ConfirmThis();";
You'll then need to add the ConfirmThis function to the Page:
Page.ClientScript.RegisterScriptBlock(GetType(), "ConfirmThis",
#"function ConfirmThis() {
if(condition) { //where condition checks the bfound element.
return confirm(""Are you sure you want to delete this?"");
}
return true;
}");
Doing this approach you're going to want to try and be able to test the bfound condition on the client side in the javascript. If the bfound value is stored in a textbox or HiddenField you should use the document.getElementById function. If the bfound value is known when you are creating the page, you can inject it into the ConfirmThis function directly, of pass it into the ConfirmThis function as a parameter.
Edit in response to your edit:
You have two options when trying to elicit a confirm from the user:
Using client side logic that is already sent to the browser to perform the confirm. This is the example that I have given above.
The "Other" option is to send the page back with a modal dialog, or using the confirm box. You will then get the user's confirmation back in a completely new postback to the server. So you'll need to rethink your logic to be able to temporarily store the information from the first post back and wait for the second post back to finalize the desired action.
Of the two examples, the first option is cleaner and requires no temporary memory and saves the user an additional postback.
Because both options are going to require you to rework the logic asking for the confirm, if at all possible I would try to convert the logic required for the condition to show the confirm dialog to be able to be performed on the client's computer with javascript.
Is there any way you can precalculate the bfound variable, or at the least, send enough information for it to be calculated on the client?
If you still feel like using option 2 after all of my pleading:
use the following code (based on http://www.dotnetspider.com/resources/1521-How-call-Postback-from-Javascript.aspx:
if(bfound)
{
//save all the information you need in temporary information
ViewState["InformationINeedToFinishAfterPostback"] = ImportantInformation;
Page.ClientScript.RegisterScriptBlock(GetType(), "postbackmethod", Page.ClientScript.GetPostBackEventReference(this, "MyCustomArgument"));
Page.ClientScript.RegisterStartupScript(GetType(), "startupconfirm",
#"if(confirm(""are you sure?"") {
__doPostBack('__Page', 'MyCustomArgument');
}");
}
Now to handle the postback add the following code to your page_load:
if(Request("__EVENTARGUMENT") == "MyCustomArgument")
{
ImportantInformation = (CastToAppropriateType)ViewState["InformationINeedToFinishAfterPostback"];
//finalize the desired action here.
}
But... I would still recommend the first option. But now you have the code you will need for both options. Also, I didn't test this code, so you're bound to encounter syntactic problems, but it gets you on the right track.
I'm not all that sure what bfound is supposed to represent, but you can't execute 1/2 way through some server code and then go back to the client- ASP.NET does not work that way.
Typically you will do the confirmation with some client side JavaScript. Google ASP.NET Yes/no confirm to find lots of different ways to do this...
Once you've done this you can then conditionally execute the server side code.
You could use the Javascript confirm() function to display a dialog box to the user with 'OK' and 'Cancel' prompts. You could then store the user's choice in a hidden field and trigger a postback. This article explains how to render Javascript code to the client using ASP.NET.
Since you are using ASP.NET you can add an attribute to your button:
btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');");
Where btnDelete is your Button.