Asp.net redirect to another page - asp.net

In my page when edit button pressed it should go to edit page with filled form elements
if (e.CommandName == "edit")
{
dataaccess.Instance.get(Convert.ToInt32(e.CommandArgument));
//code here
}
How redirect to another page with a value(e.g id)

Response.Redirect("redirectpage.aspx?id="+e.CommandArgument);

Just pass the value from First page using Query String
Response.Redirect("thankyou.aspx?id="+e.CommandArgument);
And get the value in other page's page load method using
string ID = Request.QueryString["ID"].ToString();
It's the easiest way to pass and get the variable between page but Query string is visible in Address bar chances of hacking or SQL Injection is more.
For that you can Encrypt the Query String before pass it in URL.
OR
You can use Session Variable too. which is more secure than Query String.

You can use query string for this.

Related

How to access current input in Razor form so I can add it to a query?

I have a table that has sortable headers, paging (using PagedList), with filters with a submit button (using HtmlForm Get). Using any of the filters, or clicking the headers, or page numbers should do query Get and update the table with the same querystring. However, I have a problem:
The headers and pages are action links, and the filters themselves were created using #Html.TextBox, DropDownList, etc... and have a submit button
In my ActionLink I need to be able to pass all of the parameters including the values currently in the filter form:
#Html.ActionLink("< Prev", "Index",
new {Value1 = (Value in TextBox),
Value2 = ViewBag.Something,
Value3 = ect...})
and, there is also a submit button for the filters, and if that is pressed I need to be able to add the additional information to the query string from my Viewbag which holds the sorting header value and need to send the value from the model with the pagenumber.
Is there anyway at all to do what I am trying to do?
(I have thought about turning the submit button from an input to an action link, but I still don't know how to get the current values out of Html.TextBox etc)...
EDIT
I created a new filter object, that I now send as a parameter to my controller. However, I have a some action links for the headers of my table and for pages. I don't know how I can change my filter object when they are clicked without creating an action for every header and page button in my controller. Is that even a bad idea? For example:
ActionResult NextPage(Filter filter);...
ActionResult Header1(Filter filter);...
...
If I don't do it this way...I don't know how to know which action link the user clicked...and I can't use routedatadictionary because I can only send my filter object, or a bunch of parameters not both...
Another idea would be to send all of the filter model's properties, plus the links name as in a string query then rebuild the filter in the controller...
You could try using a model! So in the Action "Index", make its parameters accepts SomeModel model. Just bind all of the inputs to it and it will automatically submit. To take care of persisting the ViewBag, you have the right idea up there where you just say new { Value1 = ViewBag.Something }. If you really want to make it even more MVC-ish, just make a field in the model for whatever the viewbag holds, and then render an Html.HiddenFor(m => m.SomeField). Hope this helps!
[HttpPost]
public ActionResult Index(SomeModel model, SomeValue value, ...)
{
//Do whatever filtering you have to do, or redirects, or w/e it is you want
return View(model);
}

pass a value into next page

I have login page, once logged in I create a session variable to store the UserName.
I've used this variable to retrieve info for this User from Account table with AccountID, name etc and I return the AccountID on the page using a label (lblAccountID).
I have a button to "Add Funds" to this account, which redirects to the AddFunds.aspx page
How can I pass the AccountID into the AddFunds.aspx page which will be used to insert details into Funds table which has the AccountID.
I don't want the AccountID to be visible on the AddFunds.aspx page.
there are multiple ways to achieve this. i can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request. QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters.More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″);
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: "How to: Pass Values Between ASP.NET Web Pages"
You need to store it in a session variable:
int AccountIdVar;
Session["AccountID"] = AccountIdVar;
then you can retrieve later by
int AccountIdVar = (int)Session["AccountID"];
You can either use the session variable you stored in the previous page as it should still be accessible or another way is to pass the id over via a querystring such as www.foofoofoo.com?Id=23456.
As the others said, you can use Session or Querystring values. You can also just POST to the new page
The How To Pass Values Between Pages page is worth looking at too.
The MSDN article about Pass Values Between ASP.NET Web Pages is the best place to look for.
For this we can also use Global variable, create a module class in that declare all variables with public data type, then assign the values. Once the value is assigned it can be accessed from anywhere.

How to implement login session in asp.net and C#

I'm new to asp.net and C# and I want to ask how to implement a session login using asp.net and C#.
Please advise.
Thanks.
In C# you can define a session variable like this:
Session["userame"]= txtusername.Text;
where txtusername is a text box. In another page you can call it as:
string usrname = Session["username"].ToString();
To check whether a user is logged in or not, in a particular page; you'll have to check if this session is empty or not. If the session is null then redirect the user to login page else he/she can view the page. Same logic applies to all the pages where you want to implement the session validation. Sample (on Page_Load event):
if (Session["username"] == null)
Response.Redirect ("Login.aspx");
Hope it helps... :)
The question is broad answer, in Simply you can follow like this
Create database, user table in sql server or any database of your choice
Create the login form with userid and password
Check them with database for user availability
If User exist and password matches create a session, like Session.Add ("Userid", txtUserid.Text);
In other pages (restricted pages where only registered users allowed) write this code in every page load event
if (Session["Userid"] == null)
Response.Redirect ("Login.aspx");
Session["login_user"] = "[username]";
string username = Session["login_user"].ToString().Trim();
Easiest way to implement session is as following:
Session["SessionName"] = Value;
For retrieving value
String variable = Session["SessionName"].ToString();
Note: Session variable can be of any type.
Generally session is used for checking whether the user is logged in or not.

Preventing Re-submission of data on Browser Refresh

I have a form. On submit of a button, it inserts a record into the db. If I go back in my browser and refresh the page it's resubmitting it causing all sorts of issues as you can imagine. How do I ensure that the user can't refresh the previous page and the state of that page does another automatic submit on refresh like this?
I'm not using ViewState. I actually have it disabled in the page directive
No, Response.Redirect does NOT solve this problem. The user can still go back with the browser's back button and refresh at the point where they submitted and it will still run the button's event sending the data downstream to my DL insert
The solution I use most often is this:
When the user first visits the page (Non-PostBack), generate a token value (GUID is easy). Take this token value and store it in their Session variables and a hidden field in the page. Being a field, this value should persist through round trips to the server without ViewState enabled (I could be mistaken on that count, so please check it!). Should the page be refreshed (and form values lost), a new value will be generated by the Non-PostBack initialization.
When the page is posted back, retrieve the hidden field value and compare it against the expected value in the user's Session variables:
If the tokens match, accept the submission as "genuine", remove the token from the Session variables, and continue your workflow.
If the token is missing from Session variables, the user is trying to submit the form again. - If the tokens do not match, the user is "replaying" an old submission of the form.
Example code to achieve this sort of solution:
public partial class MyPage : Page
{
protected HiddenField tokenField;
protected void Page_Load()
{
if(!IsPostBack)
CreateToken();
}
// Call this method to establish a token in session and on the page.
private void CreateToken()
{
string token = new Guid().ToString();
Session["dupeToken"] = token;
tokenField.Value = token;
}
// Call this method to validate the token before continuing workflow.
private bool TokenIsValid()
{
string expectedToken = (string)Session["dupeToken"];
if(expectedToken == null)
return false;
string actualToken = tokenField.Value;
return expectedToken == actualToken;
}
// Call this method when the page submission is complete to prevent re-submission.
private void ConsumeToken()
{
Session["dupeToken"] = null;
}
}
The easiest way would be to wrap the form in an < asp:UpdatePanel>. That way, all postbacks are done via AJAX and the browser will never ask you to re-submit your form.
The best two ways of doing this are:
Performing a check on a distinct field against the database
Create a hidden token in the form that uses a salt based on time. If you put logic in script to check for the existing time and compare it to the token, you can either allow the submission or define it. For example, if the form is drawn at a certain time, you store the token, and within 30-60 seconds you can submit, but after that you cannot.

ASP.NET: How to redirect, prefilling form data?

i want a handler to redirect to a web-forms page, pre-filling in the values of some controls on the form.
i tried setting my current Request.Form data:
if (theyWantToDoSomething)
{
//pre-fill form values
context.Request.Form["TextBox1"] = "test";
context.Request.Form["ComboBox1"] = "test 2";
context.Request.Form["TextBox2"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return;
}
But i get an exception that Form values are read only.
What would be a way to send the client to another page, pre-filling form data?
Answer
i used the Session state to store values. It's important to note that by default a Handler doesn't have access to Session (the Session object will be null). You have to tell IIS to give you the Session object by adding the IRequiresSessionState marker interface to your handler class:
public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
...
if (theyWantToDoSomething)
{
//pre-fill form values
context.Session["thing1"] = "test";
context.Session["thing2"] = "test 2";
context.Session["thing3"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return; //not strictly needed, since Redirect ends processing
}
...
}
}
You can only populate your Response, the Request is input data and is indeed read-only.
If you are using ASP.NET, there are a variety of ways you could accomplish what you need:
The best way would probably be to pass the data you need to be pre-populated to SomeWebForm.aspx via the Session object, and on that pages Load method, populate your form. Keep in mind that when you do Response.Redirect, a 302 response is sent to the client with the URL the client should redirect to. The process is transparent to the user...but there is a full round trip involved.
Another alternative to populating the users Session would be to add GET parameters via a query string to the redirect to SomeWebForm.aspx.
If you need to transfer processing to the SomeWebForm.aspx page without round tripping, you could use Server.Transfer. This will transfer execution from the current page to the page you choose...however, this can cause some odd behavior on the client end because the URL does not update. As far as the user is concerned, it will still appear as though they are on the same page they started on.
A few ideas that might get you started:
Pass the values in the query string
Store the values in the session state or in a seperate cookie
Store the values in HttpContext.Items and use Server.Transfer instead of Response.Redirect
Another approach that hasn't been mentioned yet is using Server.Transfer makes it possible to use the Page.PreviousPage property, allowing access to the controls on the page that transferred control.
As jrista mentioned though, using Transfer doesn't update the URL shown to the user, which may or may not be an issue. For example, a user can't precisely bookmark a page they got transferred to since the URL will be that of the original transferring page.

Resources