Keep the text of the text box through a PageLoad(); - c#

I am wondering How i can keep the text of my textbox even if i have to make a new page load, clicking on an hyperlink.
It's always an empty string.
Can someone help me ?
lkForgotten.NavigateUrl = string.Format("Logon.aspx?forgotten={0}", "");
lkSend.NavigateUrl = string.Format("Logon.aspx?forgotten={0}&userEmail={1}", "submited", txtForgotten.Text);
try
{
if (Request.QueryString["forgotten"].ToString() == "")
{
txtForgotten.Visible = true;
lkSend.Visible = true;
}
if (Request.QueryString["forgotten"].ToString() == "submited")
{
userEmail = txtForgotten.Text;
SendForgottenPassword(userEmail);
}
}
catch { }

If you need to persist some data specific to the person, you can use a session. It is precisely the thing you need.
You can set it whenever you want and get the values you need.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Edit:
To satisfy some objections raised in comments, if the session itself isn't enough, you can still use a different approach. Monitor the textboxes with javascript and if their value is changed, add a cookie (or add a value to existing cookie, depends on the needs). Still much better approach than using querystring for this type of functionality... At least in my opinion.

Edit
Do the redirection with the
Javascript code
function redirect()
{
var val = document.getElementById('<%= txtForgotten.ClientID %>').value;
location.href='Logon.aspx?forgotten=submitted&userEmail=' + val ;
}
<input type="button" VALUE="Visit Microsoft" OnClick="redirect();">
problem witht he above code is when you are creating the url of forget password on page load at that time textbox value is empty and when do redirection by clicking forget password link its getting empty value only rather what you typed in your code...so to make it work do the redirection using javascript as above or make use of click event that do the redirection for you....
Org
following line change like this
if (Request.QueryString["forgotten"].ToString() == "submited") {
userEmail = txtForgotten.Text = Request.QueryString["userEmail"].ToString() ;
SendForgottenPassword(userEmail);
}
so when you are clicking button it get the value of userEmail from the querystring and restore value in you textbox ...this will surely do your task
or
you can make use of other client side mecanisam like cookies to store the value and than retrive it back on page...
serverside option is session variable also helpfull if you want to store the value and retrieve it back.....

Related

how to create a cookie which can store list/Array

In my current project I have to show a Popup(Welcome Info) every time he/she login to the site. In the Popup user have a option(Onclick CheckBox) to hide the Popup for 30days.
I'm achieving this by saving a UserUniqueId to cookie(Which should be an array/list) when he/she click checkBox on popup. As Below
var UniqueId = "xxx";
var uIDCookies = [];
// looping to get all the values that are stored in cookie
$.each($.cookie(), function(i, v) {
uIDCookies.push(i);
});
// if current userUID not found in cookie then showing popup
if (($.inArray(UniqueId, uIDCookies)) === -1) {
//show popup
} else {
// hide popup
}
// create cookie and set expire time
$('.checkBox').on('click', function () {
var date = new Date();
var minutes = 3;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie(UniqueId, { expires: date, path: '/' });
//hide popup
});
No matter what I'm looping through all cookie values that are stored on client browser so, I feel that there could be a better way to achieve this. Suggestions Please..!!
You are saving the cookie with the UniqueID as the name. Just check if that cookie already exists directly:
if (! $.cookie(UniqueId) ) {
//show popup
} else {
// hide popup
}
This sounds very suspiciously like a very bad design choice, but to answer the question as asked, just serialise the array and convert the string to Base64. Then you can parse it back out again afterwards.
As mentioned in the OP's comments though, there are very few edge cases where this is necessary in the scenario you have mentioned. Also, don't set or get cookies in jQuery. Use your serverside language to gather and set cookie information whereever possible, and send it to the page where needed. Don't use cookies where it would be better to use a data store. You have no control over the cookie information once it has been set, and so they can be a security vector into your application.
Cookies are stored per profile, per browser, per user, per computer, and so aren't always the best way to store this info. Instead, consider adding two columns to your user profile table, DisplayWelcomeMessage as a boolean, and SuppressWelcomeMessageExpiry as a DateTime. That way, the info is set per user, not per cookie. It allows the application to be more scalable, as it gives the user the option to turn it back on before the expiry runs out.

MVC javascript redirect page not working

In MVC, the default views for a controller allow one to reach the edit page via selecting an item in an index and using that id to reach the specific edit page.
In this MVC edit page, I have a javascript that reacts to a change in a dropdown. The dropdown represents a subset of the potential id's available from the index page, and in general, someone will choose a different one than the currently displayed one.
The postback to the control works correctly in C#, and I can find the relevant model that goes with the id. It all appears correct on the C# controller side. However, when I try to get it to redirect back to the same edit page but with a different id (that from the dropdown), the page reverts back to the ajax call.
Is there anyway to "short-circuit" the ajax call so that it "knows" that it doesn't return but lets the C# redirect to the edit page (just like what happens when an element is chosen from the index page).
Thanks in advance,
Joseph Doggie
If you are making ajax requet, then you have to implement a way to redirect.
Depends on your ajax protocol... Are you returning json? html ...
If returning json, you could add a flag in your response telling wether this is a redirect answer and do redirect in js :
window.location = url
OK, there is at least one way to do this.
Assume editing X with Controller named YController:
JavaScript:
var MyControllerUrlSettings = {
MyControllerPrepareModifyXInfoUrl: '#Url.Action("PrepareModifyAssetInfo", "Y", new { x_txt = "param" })'
}
one then has a JavaScript to handle the dropdown change:
$('#ModelXList').change(function () {
//// alert('Change detected');
if ($("#ModelXList").val() != "") {
//// alert('Reached here');
var XNbrString = $("#ModelXList").val();
var trimmedXNbrString = $.trim(XNbrString);
//// debugger;
if (trimmedXNbrString != "") {
var url = MyControllerUrlSettings.MyControllerPrepareXInfoUrl;
window.location.href = url.replace('__param__', trimmedXNbrString);
}
}
else {
}
});
Finally, in the controller, there is a method:
public ActionResult PrepareModifyXInfo(string XNbr_txt)
{
// we cannot save anything here to cdll_cdcloanerlist;
// static variables must be used instead.
/// .... do what you have to do....
return RedirectToAction("ModifyEdit", new { XNbr_txt = XNbr_txt });
}
Note: For proprietary reasons, I changed some of the syntax so that everything would be general, therefore, you may have to work with the above code a little, but it works
Alternate answers are really welcome, also!

Altering a value between form submit and TryUpdateModel

I am probably missing something ready obvious. However, after trying to crack this all morning, I have gotten nowhere.
I am using Reverse Engineered Code First Entity Framework on my Web Form app.
I am attempting to update a submitted value before calling TryUpdateModel and can't seem to figure it out.
Here is my current code:
public void frmOrganisation_UpdateItem([RouteData] int id)
{
Website.Models.CrmOrganisation item = null;
var query = from o in db.CrmOrganisations
where o.OrganisationId == id
select o;
item = query.Single();
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
return;
}
TryUpdateModel(item);
if (ModelState.IsValid)
{
db.SaveChanges();
Response.Redirect(Helper_Methods.AppendQueryStringToUrl("status", "Changes Saved!"));
}
}
One of the fields on the form is a textbox (id: txtWebsite) which is looking for a URL to be entered. I will be storing the full URL (http:// included) in the databse. However, I don't want users to have to enter the http://. Therefore, I want to intercept the value submitted and, if it doesn't start http, I want to prefix it. Only then do I want TryUpdateModel (and therefore validation) to occur.
Can anyone point me in the right direction?
Chris.
UPDATE - I've gotten alittle further.
Between my "TryUpdateModel" and "if (ModelState.IsValid)", I now have the line "if (ModelState["Website"] != null && !string.IsNullOrWhiteSpace(ModelState["Website"].Value.RawValue.ToString())) ModelState["Website"].Value = new ValueProviderResult("http://" + ModelState["Website"].Value.RawValue, "http://" + ModelState["Website"].Value.RawValue, CultureInfo.CurrentCulture);".
This is updating the model state, however, these changes are not being reflected in the database so I presume "db.SaveChanges();" is not seeing my change.
I've found a solution.
I'm updating the fields according on the OnClick event of the button that then issues the command to the update method. So, use clicks button --> OnClick event fires and updates form --> UpdateItem method gets called and updates the model and database.

save a certain number into session on href in ASP.Net, C#

I already found this on this website.
how to pass session variable in href
But what I want is vice versa. and I can't get it done..
I need some correct syntax..
is it ......
..../home.aspx?<%Session["egSession"]=1%>
or
..../home.aspx?=<%Session["egSession"]=1%>
or
..../home.aspx?<%=Session["egSession"]=1%>
But i believe all of the above are wrong.. coz none of them are working..
Tkz..
Session.Add("egSession", 1) will add 1 to the session cookie egSession.
You could also probably be sure it doesn't already exist by doing so:
Session.Remove("egSession");
Session.Add("egSession", 1);
To get the querystring value from the address you would (code behind do)
var value = Request["egSession"];
So that means you could do:
Session.Remove("egSession");
Session.Add("egSession", Request["egSession"]);
Hope that helps!
** UPDATE **
If you can't touch the .cs files, you can do this in the ASPX-file, by wrapping your code in <% ... code goes here ... %>
if the new session variable value is know, e.g. 1 in your sample setting it can be done anywhere
<% Session["egSession"]=1; %>
if you want to pass it through as a query parameter do this:
..../home.aspx?egSession=<%=Session["egSession"]%>
The point is, you need a name for the value, i.e. egSession but you may call it what ever you want.
However, if you alldready know the value you can simply do:
..../home.aspx?egSession=1
From what I am understanding you want something like this:
APage
Take Me home
Home.aspx.cs: the code behind page, in say the OnPageLoad Event
Session["egSession"] = Request.QueryString["egSession"];
Home.aspx
<div>Session: <% =Session["egSession"] %></div>
<div>Query String: <% = Request.QueryString["egSession"] %></div>
If you are trying to to it all in one I would try the following:
APage.aspx.cs
Create a public method (change the type of the input parameter if needed)
public string SessionMagic(object input)
{
Session["egSession"] = input;
return Session["egSession"].ToString();
}
APage.aspx
A Link
*UPDATE: *
If you can not update the .cs files you can add server side code in the aspx page, not great practice but it can be done. Encapsulate the code in script tags with the run a server attribute set. E.g.:
<script runat="server">
public string ServerSideFunction(string input)
{
Session["egSession"] = Request.QueryString["egSession"];
public string SessionMagic(object input)
{
Session["egSession"] = input;
return Session["egSession"].ToString();
}
}
</script>
you can use javascript with cookie to store the value that you want to set into Session.
eg:- url- url.apsx/egValue=1 read this url using javascript. Put the key and value into cookie.
Then you can read cookie value from server and put it into session.
hope it helps.

Redirect without post back

I have a user registration form. Here I have link to another page (card info page) which has to be filled for the registration. User fills the few fields in the user registration form and click on the link that takes to card info page. When user clicks the link in card info page to navigate back to registration page, the previous details entered in registration got vanished. So I need to redirect from card info page to registration page without postback. How can i accomplish that?
Response.Redirect() is used for redirection.
You can't do this without a postback I don't think. I'd recommend storing the details from your registration page in session state then if the user returns to that page, re-populate the fields from session state.
//eg in registration page
protected void CardInfoLink_Click(object sender, EventArgs e)
{
//store details entered
Session["Registered"] = true;
Session["Username"] = txtUserName.Text;
//etc for any other fields
Response.Redirect("~/CardDetailsPage.aspx");
}
then in the Page_Load method you could, if the session data exists, pre-populate the form from session. e.g
if (!Page.IsPostback && (bool)Session["Registered"])
{
txtUserName.Text = (string)Session["Username"];
//repopulate other fields as necessary
}
When you redirect to another page it will lose all the context of that first page unless you do something to stop it. The options that spring to mind are:
Create the card info page in a popup window. This will mean that your main window is unchanged in the background. You'd preferably use purely client side code to do this but if you need server side code to do it its still possible, just slightly more fiddly.
Save the information on postback before redirect. This could either be just in session or in a database or you could even do it clientside in cookies if you want. Then when you revisit the page you can check if you have saved information and load it up automatically.
If you redirect the user to another page all captured info on that screen WILL be lost. View-state is not kept on redirects, but only on post-backs / callbacks
The only way to maintain information across redirects is to make use of Session Variables, Cookies, or even persisting the data to a Database / XML file and repopulate on return to that page.
I would suggest you save your info as the user gets directed to the info card, then on return, check for the values and re-populate it.
You can store the values in ViewState/Session and redirects to another page (card info page) and then re-populate the values when returning to registration page. Or showing pop-ups or panels (show/hide using Visible property) in the same page you can retain the user inputs. (If you are used server side controls the values are not cleared).
Server.Transfer() will perform a transfer to another page on the server-side.
Update: it would be possible to populate the current pages Context.Items property with the state originally being transferred by query string. This behaves similarly to session state but is limited to the current request.
Update 2: the Server.Transfer() method has an overload that accepts a bool parameter preserveForm, this preserves query string parameters:
http://msdn.microsoft.com/en-us/library/aa332847(v=VS.71).aspx
You can use any kind of ajax request on "go to the next page" button click to copy the registration data into session. Then after the returning you can populate the data again and to remove the session. Your code should be similar to this one:
----------------jquery ajax request-----------------------
function SetValuesIntoSession(value1, value2, value3) {
$.ajax(
{
type: "POST",
url: WebServicePathAndName.asmx/InsertIntoSessionMethodName",
contentType: "application/json; charset=utf-8",
data: "{value1:'" + value1 + "', value2:'" + value2 + "', value3:'" + value3 + "'}",
dataType: "json",
success: function(response) {
if (response.d == "Yes") {
//do something in correct response
}
if (response.d == "No") {
//do something for incorrect response
}
},
error: function(xhr) {
alert('Error! Status = ' + xhr.status);
}
});
}
below is the code for the web service, that should insert the data into the session. Note, that you must set "EnableSession = true" if you want to use session state in your web service
---------------------WebServicePathAndName.asmx------------------
[WebMethod( EnableSession = true )]
public void InsertIntoSessionMethodName( string value1, string value2, string value3 )
{
Session[ "value1" ] = value1;
Session[ "value2" ] = value2;
Session[ "value2" ] = value3;
}
I think, that the rest of the code should be easy to be implemented.

Categories