Saturday, March 24, 2012

Pass Variable through URL

Hi, I'm new to programming I want to know how to pass variable through URL
for example
http://localhost/index.html?username=check
then when the index page finish loading it can show up:
your name is checkWelcome to the ASP.NET forums, iwinmac.

Let me know whether you're learning C# or VB.NET, and I'll write an example in that language.

By the way, you wouldn't really want to put usernames into the URL like that. If you're planning to introduce a login system, you should look at theSecurity QuickStart tutorial.
I like to learn in VB.NET. I put username into the URL just for example. once I know how to get the variable from the URL I can put more stuff in to it.
use the following code in order to retreive the username into a string:

dim username as string = request.querystring("username")

If "http://localhost/index.html?username=check" was entered into a browser than the string would return "check"

As SomeNewKid2 said, The QuickStart Tutorials are always a great place for information.
Here is the code for your firstpage.aspx, where you ask the user for his or her username:

<%@. Page Language="vb" %>
<script runat="server"
Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs)

' get the user's name from the textbox
Dim Username As String
Username = UsernameTextbox.Text

' we need to "encode" the username
' so that "Charlie Brown" becomes "Charlie+Brown"
Dim UsernameEncoded As String
UsernameEncoded = HttpUtility.UrlEncode( Username )

' now, we can move off to the next page
Response.Redirect( "secondpage.aspx?name=" & UsernameEncoded )

End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
Please enter your username:
<asp:Textbox id="UsernameTextbox" runat="server" />
<asp:Button id="SubmitButton" text="Submit" onclick="SubmitButton_Click" runat="server" />
</form>
</body>
</html>




Here is the code for secondpage.aspx, where you receive the username and display it:
<%@. Page Language="vb" %>
<script runat="server"
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

' get the user's name from the querystring
Dim UsernameEncoded As String
UsernameEncoded = Request.Params( "name" )

' we need to "decode" the username
' so that "Charlie+Brown" becomes "Charlie Brown"
Dim Username As String
Username = HttpUtility.UrlDecode( UsernameEncoded )

' now, we can display the username
WelcomeMessage.Text = "Welcome " & Username

End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Label id="WelcomeMessage" runat="server" />
</form>
</body>
</html>




This is very simple. You would want to add a "RequiredFieldValidator" to ensure that the user actually enters a username.

However, I'll leave that as part of your learning.

I hope this gets you started. Any questions, please ask.

0 comments:

Post a Comment