I would like the data that i enter in a text box on pageA to be accessable on pageB
eg: User enters their name in text box on page A
page B says Hello (info they entered in text box)
I heard this can be accomplished by using a session but i don't know how.
can someone please tell me how to setup a session and how to store data in it?
Thank you!
Session["valueName"]=value;
or
Session.Add("valueName",Object);
And You can retrieve the value in label (for Example) By
/*if String value */
Label1.Text=Session["valueName"].ToString();
or
Label1.Text=Session.item["valueName"].ToString();
And also You can remove the session by;
/*This will remove what session name by valueName.*/
Session.Remove( "valueName");
/*All Session will be removed.*/
Session.Clear();
// Page A on Submit or some such
Session["Name"] = TextBoxA.Text;
// Page B on Page Load
LabelB.Text = Session["Name"];
Session is enabled by default.
Yes, you could do something like JohnOpincar said, but you don't need to.
You can use cross page postbacks. In ASP.Net 2.0, cross-page post backs allow posting to a different web page, resulting in more intuitive, structured and maintainable code. In this article, you can explore the various options and settings for the cross page postback mechanism.
You can access the controls in the source page using this code in the target page:
protected void Page_Load(object sender, EventArgs e)
{
...
TextBox txtStartDate = (TextBox) PreviousPage.FindControl("txtStartDate ");
...
}
You can use session to do this, but you can also use Cross Page Postbacks if you are ASP.NET 2.0 or greater
http://msdn.microsoft.com/en-us/library/ms178139.aspx
if (Page.PreviousPage != null) {
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null) {
Label1.Text = SourceTextBox.Text;
}
}
There is even a simpler way. Use the query string :
In page A :
<form method="get" action="pageB.aspx">
<input type="text" name="personName" />
<!-- ... -->
</form>
In page B :
Hello <%= Request.QueryString["personName"] %> !
Related
I have in Site.Master:
<% if(Session["msg"]!=null) Response.Write(Session["msg"].ToString()); %>
I have also on submit form method:
protected void Send_Click(object sender, EventArgs e)
{
Session["msg"] = "Thx for email.";
Response.Redirect("~/Default.aspx");
}
But now when I refresh page or go to another page I still see "Thx for email." but user should see it only once.
You can clear out the Session["msg"] on Page_load (outside of the if(!isPostback))
Or you can create a label on the master page, access that through the child pages to put the message in there, and clear that one on Page load, this gets you away from using Session. Using a Label you can also set the cssClass, allowing bolding, color changes (red for errors, green for success, etc).
If you just want a plan message you could aways go with a literal control, less over head.
This is because Session variable having their value throghout the session.
Session["msg"]
will always have same value on all the pages in a session.
If you want that value should only be used for the page where you redirect then you can use querystring.
protected void Send_Click(object sender, EventArgs e)
{
Session["msg"] = "Thx for email.";
Response.Redirect("~/Default.aspx?msg='true'");
}
then on SiteMaster
<% if(Request.QueryString["msg"]!=null) Response.Write(Session["msg"].ToString()); %>
You have to set Session["msg"] = null after you show the message. Session lives in server at defualt of 20 min. If you do not set it null it will appeear
Try setting the Session["msg"] to null once it is printed on the page.
Following is the scenario I am facing, I have a aspx page in which I have added my ascx user control, I also have a <a href control which call a js function to open a aspx popup.
when I open the popup, I need to send the data present in the ascx control to my popup. can you please guide me what method can I use to achieve this other than using session, as the data can be updated in many different places hence maintaining in session will be difficult.
Thanks
try with these syntaxe ( RegisterStartupScript + window.open)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "newWindow", "window.open('Test.aspx?ID=" + _cId + "','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30);", false);
You said that you are using a js function to open the aspx popup.
then it is simple.
1. Read the Data from the controls of the User control by using javascript
var variable1 = document.getElementByID("ControlId").value;
var variable2 = document.getElementByID("ControlId").value;
2. Pass this data as query string to the next page
window.open("http://www.w3schools.com?id=" + variable1 + "&name=" + variable2);
You can read this data from querystring from the next page
If you cant sent data as querystring , can try some other ways
1. Try to post the form to the other page using target="_blank".
we can dynamically change the form action if needed.
OR
2. Make use of the window.opener object from the popup to read the data from controls the opener page.
var variable1 = window.opener.getElementById("ControlId").value
Create a hidden variable in your ascx.
<asp:HiddenField runat="server" ID="hdnId" />
On page load of ascx set the value to be sent to the hidden variable
protected void Page_Load(object sender, EventArgs e){
hdnId.Value = <value to be sent to pop-up>;
}
Register a ajax manager in the code behind.
protected override void OnInit(EventArgs e)
{
RadAjaxManager.GetCurrent(this.Page).ClientEvents.OnRequestStart = "ajaxMngr_RequestStart;";
base.OnInit(e);
}
In the ajaxMngr_RequestStart() JS
function ajaxMngr_SA_RequestStart(sender, args) {
var oPatId = "<%=hdnSendPatId.Value %>";
//add code to open the pop-up, add oPatId as part of the URL
}
}
I use Telerik, which makes helps a lot in managing pop-ups. Let me know, if this helps.
Cheers!
I'm developing an blog using ASP.NET, and I want that the user can be able to add comments.
So I want to implement the idea of facebook on adding comments.
The comment will be stored in the database, so I will be able to load it with the page if the user goes to another web page.
You have any idea how can I do this thing ( Ajax, Javascript, jQuery, Ajax Toolkit ) ?
EDIT:
I found this :
<body>
<form id="form1" runat="server">
<p>
<textarea id="textArea"></textarea>
</p>
<input type="submit" value="Commenter"/>
<br />
</form>
<p>Add some Test to the page</p>
</body>
and script.js :
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
}
function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);
var newGraf = document.createElement("p");
newGraf.appendChild(newText);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
But how can I save the comment in the database, because an input button can't do this !
You don't necessarily need to use JavaScript to do this, although if you wish to do this asynchronously to provide a more responsive user experience then you will need JavaScript.
Using ASP.NET web forms, there are a number of ways this could be set up on the server side. You could use
Page methods
ASMX web services
WCF services
And call them using JavaScript from the client side. Inside of the server side code is where you will connect to the database, perform your CRUD operation and return a response back to the client that made the AJAX call.
A note on security - you'll want to sanitise the comments and mitigate SQL injection, XSS, XSRF and other types of injection attacks. The Anti-XSS library (soon to be superceded by the Web Protection library) is a good tool to leverage to do this and offers a better approach to encoding than the standard encoding in ASP.NET
Generally, if you are using GridView to display those blog post, simply add a template field into the Gridview. Inside the template filed, you put a Textbox and a Button.
When user click on the button, use your code behind to find the postID, and textbox, and save it to database, and then remember to bind the data to the gridview again.
Here is some sample code.
protected void btnBuy_Click(object sender, ImageClickEventArgs e)
{
ImageButton btnBuy = (ImageButton)sender; //Find which button is clicked.
//If that is a button, use Button btnBuy = (Button)Sender;
GridViewRow row = (GridViewRow)btnBuy.NamingContainer; //Find which gridview row //containes the clicked button
Label lblPostID = (Label)row.FindControl("lblPostID"); //Find the post ID
TextBox txtComment = (TextBox)row.FindControl("txtComments"); //Find the textbox
//Save the data to database.
//Put your code here.
//Bind the gridview with the data source which got some new data.
GridView1.DataSource = yourDataSource;
GridView1.DataBind();
}
I have a page and clicked on the button there it will open a new page containing some text boxes, user fill all the text boxes and clicked the button now first page open again and the question is : How can I get the vales of text boxes on the current page using both server-side and client-side
There is a restrictions to use of :
- Cross-paging
- Cookies
- Sessions
- Query strings
Server-side approach:
An alternate approach is to use Server.Transfer method.
On the current page:
protected void Transfer_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Server.Transfer("destination.aspx");
}
}
On the destination page:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox textBox = PreviousPage.FindControl("Parameter")
as TextBox;
if (textBox != null)
{
string parameter = textBox.Text;
Parameter.Text = parameter;
}
}
}
But Server.Transfer does come with disadvantages. The most serious is that the URL in the browser does not change. The browser still believes it has posted back and received content for the first web form, so history and book-marking suffer.
Client-side approach:
In real world I don't recommend to use this solution, this is only a workaround.
In two words: use window.name property on the client side. This property is available across page reloads it is a sort of session.
For more information see:
What’s in a window.name?
window.name Transport
Hope, this helps.
If you are using the PostBackUrl property of the button on the submitting page, you can access the controls for the "previous page" from the action page by using the following:
Dim txtBox as TextBox
txtBox = CType(Page.PreviousPage.FindControl("MyTextBox"), TextBox)
Then you'll have access programmatically to all of the properties and data for that control.
Use the cache if you can't use the Session, Querystring, Cookies and Cross Page posting.
If it is simple/primitive data, then you can go for the ViewState. Or Cache is a better option.
One more option is to have a Page level public variables, set the required values and redirect to the page for further processing.(This is not a good approach to follow)
I have the following situation:
A user will define a certain filter on a page, and on postback I will query the database using that filter and return a bunch of matching records to the user, each with a checkbox next to it, so he can choose whether to act on each of those records.
In Classic ASP / PHP I can generate a lot of controls named "chk__*" and then on postback go through all the $POST entries looking for the ones prefixed "chk".
What is the best way to do this in ASP.Net 2.0?
I can do it easily by implementing a Repeater with a Template containing the checkbox, bind the Repeater to a Dataset, and then on the second Postback, I just do:
For Each it As RepeaterItem In repContacts.Items
Dim chkTemp As CheckBox = DirectCast(it.FindControl("cbSelect"), CheckBox)
If chkTemp.Checked Then
End If
Next
However this has the slight disadvantage of giving me a HUGE Viewstate, which is really bad because the client will need to re-upload the whole viewstate to the server, and these people will probably be using my site over a crappy connection.
Any other ideas?
(I can also create the controls dynamically and iterate through Request.Form as in the old days, however, I was looking for a cleaner
Have you looked at the CheckBoxList control? You can bind it to your data set, provide text member and value member items, and it will also allow you to easily see which items are checked. There is also the ability to dynamically add more checkbox items if needed.
Do it the same way you did it in classic ASP. Use <input type="checkbox"> instead of <asp:checkbox>. You can access the raw post paramaters using Request.Form
I recommend the classic ASP solution when faced with absurd Viewstate conditions. It is sad to lose the nice features it provides, but combining some Viewstate enabled controls (asp:*) with some classic techniques (input type="...") has saved me a lot of headaches in the past.
Sometimes you just want to do something simple, and the simple solution beats "WYSIWYG" form editing.
One of the things that I have done is to record the state of a check via AJAX in the session, then on Postback (full or partial via AJAX), look in the session for the items to perform the selected action on.
The basic idea is to add an onclick handler to the checkbox that knows the id of the associated item. In the on click handler communicate this id back to the server via AJAX and record it in the session -- you'll need to communicate checkbox status as well so you can uncheck items. Have the handler for the submit control use the data about which items were selected from the session.
This way allows you to handle paged data as well, since you can set the initial value of the checkbox from the session when rendering (either full or partial) a page with checked items on it.
It might look something like this. Assuming ASP.NET AJAX with PageMethods (and ScriptManager, of course).
<script type='text/javascript'>
function record(checkbox,item)
{
var context = { ctl : checkbox };
PageMethods.Record(item,checkbox.checked,onSuccess,onFailure,context);
}
function onSuccess(result,context)
{
// do something, maybe highlight the row, maybe nothing
}
function onFailure(error,context)
{
context.ctl.checked = false;
alert(error.get_Message());
}
</script>
...
<tr><td><input type='checkbox' onclick='record(this,"item_1");'></td><td>Item 1</td></tr>
...
Codebehind
[WebMethod(EnableSessionState=true)]
public static void Record( string itemName, bool value )
{
List<string> itemList = (List<string>)Session["Items"];
if (itemList == null)
{
itemList = new List<string>();
Session["Items"] = itemList;
}
if (itemList.Contains(itemName) && !value)
{
itemList.Remove(itemName);
}
else if (!itemList.Contains(itemName) && value)
{
itemList.Add(itemName);
}
}
protected void button_OnClick( object sender, EventArgs e )
{
List<string> itemList = (List<string>)Session["Items"];
if (itemList != null)
{
foreach (string item in itemList)
{
// do something with the selected item
}
}
}
Disable the ViewState. In case it cannot be done try using Session to store the view state