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.
Related
I'm building an animal feed supplying website using C# .NET
It has those features below:
http://localhost:52000/Account/Index =>show a list of accounts (ID, name...).
Click on an ID from Index page, it leads into Detail page: http://localhost:52000/Account/Details/6cc608a5-3b4b-4c6f-b220-3422c984919a
In account detail's page, it also has 2 buttons(functions): Delete account and Edit account information.
All I want is after deleting an account (in Detail view), website will redirect to the previous available page (Index,...). Therefore I use window.location.href = "/Account/Index/"; in Delete function.
Here is my delete function with redirecting solution:
function deleteAccount(id) {
var data = { 'id': id };
$.ajax({
*//....*
success: function (result) {
if (result) {
*//redirect to the previous page (Index)*
window.location.href = "/Account/Index/";
}
}
});
}
However,after deleting and redirecting to "/Account/Index/" successfully, if Admin click on Back Button on Browser, website redirect to unavailable page (the Detail page of that deleted account: http://localhost:52000/Account/Detail/6cc608a5-3b4b-4c6f-b220-3422c984919a).
Then I tried to use window.history.back();, window.history.go(-1);, window.location.replace("/Account/Index/"); in turn instead, it worked perfectly only when Admin just deletes that account, if Admin Edits this account first then updates then deletes (Press Edit in Detail view -> Go to Edit view -> press Update -> Go back to Detail View ) --> website redirect to unavailable page (the editing page of that deleted account: http://localhost:52000/Account/Edit/6cc608a5-3b4b-4c6f-b220-3422c984919a).
function deleteAccount(id) {
var data = { 'id': id };
$.ajax({
*//....*
success: function (result) {
if (result) {
*//redirect to the previous page (Index)*
window.history.back();
// or window.history.go(-1)
//or window.location.replace("/Account/Index/");
}
}
});
}
Is that possible to remove the unavailable URLs (those include ID of deleted account) in browser? How can I handle the Back Button in Browser to go through those unavailable URLs? (http://localhost:52000/Account/Detail/6cc608a5-3b4b-4c6f-b220-3422c984919a and http://localhost:52000/Account/Edit/6cc608a5-3b4b-4c6f-b220-3422c984919a)
You could try with the following:
window.location.replace("/Account/Index/");
This is the equivalent of an HTTP redirect using Javascript.
When you use window.location.href it would be as if a user has clicked on a link and therefore you can go back to the previous URL afterwards.
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!
We are using WorldPay to process payments for a tiered membership system, for which the payment amount varies dependent upon the membership tier selected.
The payment is passed to WorldPay via a form post from a number of hidden fields, including:
<input type="hidden" name="amount" value="295.00" />
Essentially, the form is submitted via POST to WorldPay and the user follows a number of steps to process their payment. Once complete, the user is redirected to a specified confirmation page.
This appears to be the typical manner in which WorldPay accepts payments. There's an obvious issue here, in that the value of the hidden field could easily be tampered with by anyone with a basic knowledge of HTML. The form is posted directly to WorldPay, so we have no PostBack in which to validate the amount against the membership tier.
We have the option to validate the payment amount when a payment notification is returned to us from WorldPay by routing the callback through a handler before the confirmation page; however, I would like to avoid the situation where user submits a tampered form, pays the incorrect amount and receives no membership, then has to contact the company to have their money returned.
How might we validate that the amount being submitted is correct before processing payment?
Update
It has occurred to me that we have an additional problem whereby, even if we validate the form post server-side, there is nothing stopping a malicious user from spoofing the form post direct to WorldPay.
It is a vulnerability indeed, it can be solved easily using a signature. Check out this link:
http://culttt.com/2012/07/25/integrating-worldpay-into-a-database-driven-website/
This method should be better promoted on the help page, too bad.
One solution I can think of is this, capture the form tag's submit:
<form id="myForm" onsubmit="return validatePayment();">
and then create that JavaScript file that looks like this:
var isValidAmount = false;
function validatePayment() {
if (isValidAmount) { return true; }
// in here you want to issue an AJAX call back to your server
// with the appropriate information ... I would recommend using
// jQuery and so it might look something like this:
$.ajax( {
type: "POST",
url: url,
data: { amount: $("#amount").val(), someotherfield: somevalue },
success: function(data, textStatus, jqXHR) {
// set the flag so that it can succeed the next time through
isValidAmount = true;
// resubmit the form ... it will reenter this function but leave
// immediately returning true so the submit will actually occur
$("myForm").submit();
},
});
// this will keep the form from actually submitting the first time
return false;
}
I have a web form of Asp.Net, in which I want JavaScript to count how many time i have refreshed the page.
If you want to do it on clientside just save (and retrieve) the information on localstorage every time load event occurs
Do you want to count this per user ? Or for whole application ?
If you are doing for whole application you can use application variable in Global.asax on each page request . But that might get lost if your application recycles .
If you want to do for each user You can use server side sessions or cookies on clientside .
You can set the value in a cookie using js or asp, or in a session value (for a single user) or in application value (for all the users), is not necessary javascript.
You have to put this code server side on page load.
For all users:
Application["refresh_count"] =
Convert.ToInt64(HttpContext.Current.Application["refresh_count"]) + 1;
For a single user with session:
Session["refresh_count"] = Convert.ToInt64(Session["refresh_count"]) + 1;
OR
Response.Cookies["UserSettings"]["refresh_count"] = Convert.ToInt64(Response.Cookies["UserSettings"]["refresh_count"]) + 1;
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);
You can save this in the Session Object.
You can use jQuery calling prepared address.
For example:
$.ajax({
url: ".../countPageRefreshes.aspx",
data: { page: "thisPageAddress" }
})
Then, in countPageRefreshes you can increase number of times, page was refreshed and save it somewhere.
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.....