How can I recapture form data? - c#

I am attempting to recapture some form values after they have been posted, but am having quite a bit of difficulty. My form has 2 fields:
<strong>Username:</strong> <asp:TextBox ID="txtUsername" runat="server" Width="200px" /><br /><br />
<strong>Password:</strong> <asp:TextBox ID="txtPassword" runat="server" Width="200px" TextMode="Password" />
And in the code behind, I have tried to capture the username, but keep coming up empty handed. Here is my current implementation:
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "POST")
{
txtUsername.Text = Request.Form["txtUsername"];
}
}
What am I missing?

your code works perfectly fine for me:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" id="MainHTML" runat="server">
<head runat="server">
<title></title>
<script type="text/javascript">
</script>
</head>
<body>
<form runat="server">
<strong>Username:</strong> <asp:TextBox ID="txtUsername" runat="server" Width="200px" /><br /><br />
<strong>Password:</strong> <asp:TextBox ID="txtPassword" runat="server" Width="200px" TextMode="Password" />
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
cs:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "POST")
{
txtUsername.Text = Request.Form["txtUsername"];
}
}
}

Without seeing the rest of the .aspx page, there's nothing glaringly obviously wrong there, but:
are the TextBoxes within a form with runat="server"?
have you run a trace to see what the Form variables, if any, contain?
are you sure the page is being submitted, and not just refreshed?
have you tried a breakpoint to see whether the if condition evaluates to true (similar to above point)?

I would think you can add onclick= to the button that is submitting the form since the textboxes are running at server. After the equal sign if you press tab twice it will automatically generate an event in the code behind. Then you can do something like this in the code behind to save it in session.
string firstName = txtUsername.Text;
string lastName = txtPassword.Text;
Session["FirstName"] = firstName;
Session["LastName"] = lastName;
and to access it later
string firstName = Session["FirstName"];

First of all to checking if it is a post you can check with this:
if (IsPostback) { //do something here }
and you will see that if it is done on the same page will not work coz it post to itself.When you click a button in the same page data are generally saved in viewstate.So before give you more info we need to have more info about it work to better help you.

Related

Enable and disable textbox through button?(asp.net)

enter image description hereMy tutor gave me the following task: Create a form with 3 buttons(Save(Guardar) Edit(Editar) Delete(Eliminar) ).
But my real question is this:
I need to link my text box to my button allowing me to disable it and enable it at will but I can't conect them trough code.
PS:If you answer this question try as much as you can to be specific about the terms you use since I've started learning asp.net a few days ago.
enter image description here
First, you need to create the button event.
Double click to the button on your form, then the VB will create a button event automatically.
Now, you can code.
For i.e:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;//Disable textbox1 on the form
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="RedioButton.aspx.cs" Inherits="Shoping_Cart.RedioButton" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Enable Disable Textbox Using Jascript Radio Button Click</title>
<script type="text/javascript">
function EnableDisableTextBox() {
var status = document.getElementById('<%=rbtEnable.ClientID %>').checked;
if (status == true) {
document.getElementById('<%=TextBox1.ClientID %>').disabled = false;
} else {
document.getElementById('<%=TextBox1.ClientID %>').disabled = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Width="228px"></asp:TextBox>
<br />
<br />
<asp:RadioButton ID="rbtEnable" runat="server" Text="Enable" onclick="javascript:EnableDisableTextBox();" GroupName="1" />
<asp:RadioButton ID="rbtDisable" runat="server" Text="Disable" onclick="javascript:EnableDisableTextBox();" GroupName="1" />
</div>
</form>
</body>
</html>

Page_Load firing twice regardless of what i do

I am working on a simple asp.net login page. Yesterday, the code was working fine. Today, it isn't.
The only thing that changed between yesterday and today is that I shut down my pc and started it again today.
The problem is that Page_Load is firing twice (I checked all the answers/solutions, and none worked (image with empty src, handling the page_load manually, setting autoEventWireUp to false...)) none of these seemed to do the trick.
PLEASE can someone help me figure out why this is happening?
Here is the code for the page and its code behind:
<%# Page Title="Login" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="Login.aspx.cs" Inherits="MatchingWebsite.Login" MaintainScrollPositionOnPostback="true" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %></h1>
</hgroup>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2 align="center">Looking for someone to spend your time with? Want to have fun with someone you like?<br />You've come to the right place!!</h2><br /><br /><br />
<img alt="Cupid" src="Images/images.jpg" align="left" />
<img alt="Couple" align="right" src="Images/matchmaking.jpg" /><br /><br />
Username:<br />
<asp:TextBox ID="UserLogIn" runat="server" Width="174px"></asp:TextBox><br /><br />
Password:<br />
<asp:TextBox ID="UserPass" runat="server" Width="175px" TextMode="Password"></asp:TextBox><br />
<asp:Label ID="LoginError" runat="server" Text="Wrong Username/Password Combination. Try again." Visible="False"></asp:Label><br /><br />
<asp:Button ID="LoginButton" runat="server" OnClick="Login_Click" Text="Login" Width="81px" />
<asp:Button ID="NotRegistered" runat="server" Text="Not Registered?" Width="150px" OnClick="Not_Registered" />
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.auto-style1
{
width: 300px;
height: 113px;
}
</style>
</asp:Content>
And here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MatchingWebsite
{
public partial class Login : System.Web.UI.Page
{
Service1 proxy = new Service1();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"]!=null && !IsPostBack)
Response.Redirect("~/EnterMyInfo.aspx");
}
protected void Login_Click(object sender, EventArgs e)
{
string user = UserLogIn.Text;
string pass = UserPass.Text;
if (user == "" || pass == "")
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\"Username/Password cannot be blank.\")</SCRIPT>");
else
{
if (proxy.login_service(user, pass))
{
Response.Redirect("~/EnterMyInfo.aspx");
}
else
LoginError.Visible = true;
}
}
protected void Not_Registered(object sender, EventArgs e)
{
Response.Redirect("~/SignUp.aspx");
}
}
}
Likely the webpage is really loaded twice. Check your javascripts (or any AJAX components?), or use the browser's debug console to monitor the network requests being sent. Try adding empty methods on the PreInit, PostInit (etc.) events and set breakpoints too, I bet those are hit twice as well.

How can I add selected value in an asp.net ajax toolbox autocomplete to a label?

I have got the Ajax toolkit autocomplete working using the following asp.net and C# code.
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
Search our Languages: <asp:TextBox ID="txtLanguage" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtLanguage" MinimumPrefixLength="1"
ServiceMethod="GetCompletionList" UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<br />
<asp:Button ID="btnAddSelected" runat="server" Text="Add to chosen Languages >"
onclick="btnAddSelected_Click" />
<br />
<br />
<asp:Label ID="lblSelectedLanguages" runat="server" Text=""></asp:Label>
</div>
</form>
This is my codebehind C#:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
// Create array of languages.
string[] languages = { "Afrikaans", "Albanian", "Amharic", "Arabic", "Azerbaijani", "Basque", "Belarusian", "Bengali", "Bosnian", "Bulgarian" };
// Return matching languages.
return (from l in languages where l.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select l).Take(count).ToArray();
}
protected void btnAddSelected_Click(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
The selected language is added to the label when the button is clicked, however I would like to remove the button and make the selected item from the autocomplete added to the label automatically, using the partial postback from the Ajax toolkit.
Can someone please advise as to how I can achieve this?
Thanks.
Handle OnClientItemSelected on the AutoCompleteExtender control to run a javascript function
All the javascript does is simply fire off the TextChanged event when the selection is made (works on both Enter and left click)
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function ItemSelected(sender, args) {
__doPostBack(sender.get_element().name, "");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Search our Languages:
<asp:TextBox ID="txtLanguage" autocomplete="off" runat="server" OnTextChanged="TextChanged" />
<asp:AutoCompleteExtender OnClientItemSelected="ItemSelected" ID="AutoCompleteExtender1"
runat="server" TargetControlID="txtLanguage" MinimumPrefixLength="1" ServiceMethod="GetCompletionList"
UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<asp:Label ID="lblSelectedLanguages" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
Code behind:
protected void TextChanged(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
It looks like you just need to hook onto the on text changed event of your text box and then put your logic in code benind.Something like this
Markup
<asp:TextBox ID="txtLanguage" OnTextChanged="txtLanguage_textChanged" AutoPostback="true" />
Then in your code behind
protected void txtLanguage_textChanged(object sender, EventArgs e)
{
//use the retrieved text the way you like
lblSelectedLanguages.Text =txtLanguage.Text;
}
Hope this helps.I would also suggest that you try looking into the JQuery autocomplete widget.It has brought me sheer happiness and I surely did divorce the autocomplete extender.
Jquery Autocomplete

Displaying sourcecode when clicking a button

First I have to let you know that i am a newbie in this area, learning from tutorials.
With that said I'm looking for a way to load sourcecode from the codebehind file into a textbox, when clicking a button. Same goes for the aspx file.
Im making this website, where i am going to show code examples from what im doing. So if I navigate to myweb.com/tutorial1done.aspx this page would show me the final result from the tutorial done. When i click the show source button it should make 2 textboxes visible, and add the codebehind to the first box, and the aspx source to the second box.
I don't know if it is possible, but I am hoping so.
This far i have this:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DateTimeOutput.aspx.cs" Inherits="WebApplication1.DateTimeOutput" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="../styles/codeformatter.css" />
</head>
<body>
<form id="form1" runat="server">
<customControls:Header runat="server" heading="Date and Time Output" />
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:TextBox ID="outputText" runat="server" Height="175px" TextMode="MultiLine"
Width="400px"></asp:TextBox>
</asp:Panel>
</div>
<asp:Panel ID="Panel2" runat="server">
<asp:Button ID="runButton" runat="server" Text="Run Code"
onclick="runButton_Click" Width="95px" />
<asp:Button ID="clearButton" runat="server" Text="Clear Console"
onclick="clearButton_Click" Width="95px" />
<br />
<br />
<asp:Button ID="dt_showSource_btn" runat="server"
onclick="dt_showSource_btn_Click" Text="Show Source" />
</asp:Panel>
<asp:Label ID="dtLabel1" runat="server" Text="Code Behind:" Visible="False"></asp:Label>
<br />
<asp:TextBox ID="dtcb_output" runat="server" Height="175px"
TextMode="MultiLine" Visible="False" Width="400px"></asp:TextBox>
<br />
<br />
<asp:Label ID="dtLabel2" runat="server" Text="ASPX:" Visible="False"></asp:Label>
<br />
<asp:TextBox ID="dtaspx_output" runat="server" Height="175px"
TextMode="MultiLine" Visible="False" Width="400px"></asp:TextBox>
</form>
</body>
</html>
And the Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class DateTimeOutput : System.Web.UI.Page
{
protected void output(String value)
{
outputText.Text += value + Environment.NewLine;
}
protected void runButton_Click(object sender, EventArgs e)
{
DateTime dt = new DateTime();
output(dt.ToString());
DateTime nowDt = DateTime.Now;
output(nowDt.ToString());
}
protected void clearButton_Click(object sender, EventArgs e)
{
outputText.Text = "";
}
protected void dt_showSource_btn_Click(object sender, EventArgs e)
{
if (dtcb_output.Visible == false)
{
dtLabel1.Visible = true;
dtcb_output.Visible = true;
}
else
{
dtLabel1.Visible = false;
dtcb_output.Visible = false;
}
if (dtaspx_output.Visible == false)
{
dtLabel2.Visible = true;
dtaspx_output.Visible = true;
}
else
{
dtLabel2.Visible = false;
dtaspx_output.Visible = false;
}
}
}
}
For now source highlighting is not needed, unless its easy to do.
Thx in advance.
If you're refering to the actual code of your code behind file, you have a problem. As the file will be compiled and then be placed as intermediate code in a dynamic link library (.dll), you don't have access to the .aspx.cs file any more. The only way to go would be to include the code behind file with the deployd project and open it with a FileStream (or whatever) to read it and display it's content.

How to make a “asp:Button” work inside a “mmenu nav “

I’m trying to integrate “jquery.mmenu” in a Visual Studio project.
It seems that “asp:Button” does not work inside a “mmenu nav “.
Nor a "asp:LinkButton" seems to fully perform.
Take the specific case of a login:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="test._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery-ui-1.11.4.min.js"></script>
<script src="Scripts/jquery.mmenu.min.all.js"></script>
<link href="Content/themes/base/all.css" rel="stylesheet" />
<link href="Content/themes/base/jquery.mmenu.all.css" rel="stylesheet" />
<title></title>
<script>
$(document).ready(function () {
$("#login").mmenu({
});
});
</script>
</head>
<body>
<div>
<form id="form1" runat="server">
Open login pannel<br />
<asp:LoginStatus ID="LoginStatus1" runat="server" LogoutAction="Redirect" LoginText="login" LogoutText="logout" LogoutPageUrl="~/" /><br />
<nav id="login">
<div>
<asp:Label ID="UserNameLabel" runat="server">User:</asp:Label><br />
<asp:TextBox ID="UserNameTextBox" runat="server"></asp:TextBox><br />
<asp:Label ID="PasswordLabel" runat="server">Password:</asp:Label><br />
<asp:TextBox ID="PasswordTextBox" runat="server" TextMode="Password"></asp:TextBox><br />
<asp:Button ID="LoginButton" runat="server" ClientIDMode="Static" Text="Login Button" OnClick="LoginButton_Click" /><br />
<asp:LinkButton ID="LoginLinkButton" runat="server" ClientIDMode="Static" OnClick="LoginLinkButton_Click">Login LinkButton</asp:LinkButton>
</div>
</nav>
</form>
</div>
</body>
</html>
The code behind looks like:
using System;
using System.Web.Security;
namespace test
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoginButton_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(UserNameTextBox.Text, PasswordTextBox.Text))
{
FormsAuthentication.RedirectFromLoginPage(UserNameTextBox.Text, false);
}
}
protected void LoginLinkButton_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(UserNameTextBox.Text, PasswordTextBox.Text))
{
FormsAuthentication.RedirectFromLoginPage(UserNameTextBox.Text, false);
}
}
}
}
The asp:Button does not post back.
The asp:LinkButton does not login.
Is there a way to have it working?
Thanks.
Web forms most of the time change the name of the element and jquery needs the exact name to find your button. Add this property to your button and test again
ClientIDMode="Static"
The mmenu plugin grabs the NAV#login from the HTML and puts it back directly inside the BODY. Meaning, the input and button are no longer inside the FORM (and thus won't submit the form).
Basically, if you put the FORM inside the NAV#login all should work as expected.

Categories

Resources