Using AJAX to send create new user details via asp.net - c#

What's the best way to send a username and password via ajax to the code behind page in .net.
I have an index.aspx page like so:
<asp:TemplatedWizardStep>
<CustomNavigationTemplate>
<div style="margin-bottom:7px;text-align:left;">To create an account, simply send us your e-mail address. A password will be sent to this address upon submission.</div>
<table border="0" cellpadding="3" cellspacing="0" style="width:99%;">
<tr>
<td style="text-align:left; vertical-align:middle;width:90px;">E-Mail:</td>
<td style="text-align:left; vertical-align:middle;">
<asp:TextBox ID="UserName" runat="server" CssClass="newUserTextbox"></asp:TextBox>
</td>
</tr>
<tr>
<td style="text-align:left; vertical-align:middle;width:90px;padding-top:5px;">Screen name:</td>
<td style="text-align:left; vertical-align:middle;padding-top:5px;">
<asp:TextBox ID="ScreenName" runat="server" CssClass="newUserTextbox"></asp:TextBox>
</td>
</tr>
<tr>
<td style="text-align:left; vertical-align:middle;"> </td>
<td style="text-align:right; vertical-align:middle;padding-top:5px;">
<asp:imagebutton ID="CreateUser" CommandName="CreateUser" Enabled="true" runat="server" AlternateText="OK" ImageUrl="powerstats/inc/img/ok_up.png"></asp:imagebutton>
<img src="powerstats/inc/img/cancel_up.png" style="cursor:pointer;" onmouseover="SwapImageIndex(this,'cancel_ov.png')" onmouseout="SwapImageIndex(this,'cancel_up.png')" />
</td>
</tr>
</table>
</CustomNavigationTemplate>
</asp:TemplatedWizardStep>
I want the imagebutton to be clicked and send an ajax call with the username and screenname (and eventually password), to the back end page. If I do onClick=X the page refreshes. I want the page NOT to refresh and send an alert back if something is wrong.

You would need to use an UpdatePanel with a ScriptManager. If a submit happen inside the UpdatePanel, it's gonna return only what's inside the UpdatePanel itself through AJAX.
If you want to handle possible Error, you can use the AsyncPostBackError Event of the ScriptManager. See MSDN page for a complete exemple of error handling.
Code would look like (+ your error handling logic):
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TemplatedWizardStep>
<CustomNavigationTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
/* Your login controls here ...
Make sure to include all the fields
to be refreshed + the submit button */
</ContentTemplate>
</asp:UpdatePanel>
</CustomNavigationTemplate>
</asp:TemplatedWizardStep>

Related

Control 'txtUserName' of type 'TextBox' must be placed inside a form tag with runat=server

I have this error - Control 'txtUserName' of type 'TextBox' must be placed inside a form tag with runat=server. I am unable to get rid of it, my text box is placed inside a form tag with runat=server.
The page which I am getting this on is my 'reset password' page I want the users to be able to enter their username and once they press the reset password button it takes them to a page which allows them to change their password.
Here is the code that I am currently working with.
<head runat="server">
<title></title>
</head>
<body>
<div style="font-family:Arial">
<table style="border: 1px solid black; width:300px">
<tr>
<td colspan="2">
<b>Reset my password</b>
</td>
</tr>
<tr>
<td>
User Name
</td>
<td>
<form action="ChangePassword.aspx" method="get">
<asp:TextBox ID="txtUserName" Width="150px" runat="server"
ontextchanged="txtUserName_TextChanged">
</asp:TextBox>
</form>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnResetPassword" runat="server"
Width="150px" Text="Reset Password" onclick="btnResetPassword_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
</body>
</html>
As the error message says, you need to add a runat="server" in the form tag. This is just something ASP.NET demands to work.
The way ASP.NET handles events and postbacks forces this requirement. It tries to keep the page's state inside the actual page (called the 'view state'), and on form submission it sends it back. This was invented to make the stateless web stateful.
Just put in the runat="server" inside the form tag and you will be set.
<form runat="server" action="ChangePassword.aspx" method="get">
Add < form> tag like this...,
it will work..

Update panel in master page and asp fileupload in child page

i'm facing a problem, currently i'm having a update panel in my master page and in one of my child page i'm having a asp fileupload control.
My update Panel in master p[age:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:updateprogress associatedupdatepanelid="UpdatePanel1"
id="updateProgress" runat="server">
<progresstemplate>
<div id="processMessage" style=" background-image:url('../../Styles/ajax-loader3.gif'); width:100px; height:100px; background-repeat:no-repeat; background-position:center;">
</div>
</progresstemplate>
</asp:updateprogress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
..
</ContentTemplate>
</asp:UpdatePanel>
</form>
My Child page which needs a fileupload:
<div id="Annoucments" class="ContentDIV">
<h2 class="Tabheader">Annoucments</h2>
<p class="tabdescription">Here you will be able to upload announcements and pictures to be displayed in the login page, below is the current announcement click on update to save the changes that you have made.</p>
<table width = "100%">
<tr>
<td class="Tablabel">Annoucment title:</td> <td class="tableInput" align="left"><asp:TextBox ID="Announcement_TB" runat="server" CssClass="textboxTabs"></asp:TextBox></td>
<td class="Tablabel">Picture/Poster:</td> <td class="tableInput" align="left"><asp:FileUpload ID="Announcement_PIC" runat="server" CssClass="textboxTabsFiles"/></td>
</tr>
<tr>
<td class="Tablabel">Description:</td> <td class="tableInput" align="left"><asp:TextBox ID="Announcement_Desc" CssClass="textboxTabs" runat="server" Rows="3" TextMode="MultiLine"></asp:TextBox></td>
</tr>
<tr><td colspan="4" style="height:10px" id ="BLANK">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td></tr>
<tr>
<td colspan="2" align="right"><input type="button" id="Announcement_Update" runat="server" value="Update" class="TabButton" onserverclick="ANNOUNCEMENT_UPDATE_Click" style=" font-size:smaller"/></td><td colspan="2"> <input type="button" ID="ANNOUNCEMENT_Cancel" runat="server" value="Cancel" class="TabButton" style=" font-size:smaller"/></td>
</tr>
</table>
</div>
*When i click the button Announcement_Update backend codes will be triggered to get my filename, the file name returned will always be "" found out while debugging.*
Put this code in child page, to pass PostBackTrigger for file upload.
protected void Page_Load(object sender, EventArgs e)
{
UpdatePanel updatePanel = Page.Master.FindControl("UpdatePanel1") as UpdatePanel;
UpdatePanelControlTrigger trigger = new PostBackTrigger();
trigger.ControlID = Announcement_Update.UniqueID;
updatePanel.Triggers.Add(trigger);
}
enjoy coding :)
You can't get filename inside that UpdatePanel
either remove that UpdatePanel from your code or use Asynchronous File Uploader,
Alternatively you could use Ajax File Uploading techniques this is a little tricky though.
Asp UpdatePanel not work inside a update panel duw to postback issue.
You can add trigger with the button assosiated with uploader like
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
It works for me if you add the Trigger, but also make sure to edit to form tag to include:
<form runat="server" enctype="multipart/form-data">

submit a form with AjaxToolkit?

Can we submit a form in ASP.NET with AjaxToolkit ?
e.g:
below in our form:
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div id="mainDiv">
<table style="width: 40%;" cellspacing="3" cellpadding="3">
<tr>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorUsername" runat="server" ErrorMessage="*"
SetFocusOnError="True" Text="*" ControlToValidate="TextBoxUsername"
ValidationGroup="login"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBoxUsername" runat="server"></asp:TextBox>
</td>
<td align="left">
: UserName
</td>
</tr>
<tr>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
SetFocusOnError="True" Text="*" ControlToValidate="TextBoxPass"
ValidationGroup="login"></asp:RequiredFieldValidator>
<asp:TextBox ID="TextBoxPass" runat="server" TextMode="Password"></asp:TextBox>
</td>
<td align="left">
: Pass
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="ButtonSubmit" runat="server" Text="Login"
ValidationGroup="login"/>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="LabelResult" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
I wanna log-in a user with Ajax so I have to send username and pass to a Webservice and get the result and show the result in LabelResult.
Can we do it with AjaxToolkit in ASP.Net?
I'm using ajax for a cascading dropdown menu set and i don't know how to submit the contents of the form to a controller. I think this is a related question becausewht I did was generate a hidden ajax control that triggered upon the change in value of the final ajax control in the form. The webservice that the control triggered then saved al of the form information to a database at which point the submitbuton was more of a comforting decoration for the user. Once the user submitted the form the values were available in a meta data field in the database and the submit handler accessed those values rather than reading them from the postback.
I didthis because it ended up being faster than learning what I needed to in order to read them form the postback using java script or some other method of retrieval form the postback so I wouldn't claim thatthisis the best approach but it worked for me. Hope this helpsyou somehow.
D.A.P.
for working of AJAX script manager must appear before the form which i think not possible and also
Cos Callis says very well
"If you want to submit the form, that is what a post back is for"
So, If we wanna send a form to server with Ajax, we have to use something like JQuery, and we can't do it with AjaxControlToolkit.

ASP.Net Button not raising postback

I've a simple page in one of our web applications, which has the following markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NewUpload.aspx.cs" Inherits="Mass_Upload.NewUpload" MasterPageFile="~/Master" Title="Document Mass Upload" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link rel="Stylesheet" type="text/css" href="./../CSS/ScrollingTable.css" />
<script type="text/javascript" src="../Help/HelpPopup.js" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="CenterH1" runat="server">
Document Mass Upload <img style="Border:None;" src="../Help/help_icon.gif" />
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="CenterBody" runat="server">
<h3>Add New Upload</h3>
<table class="list">
<tr>
<td class="label" style="text-align:right;">Local File:</td>
<td class="normal">
<asp:FileUpload ID="fuFilename" runat="server" Width="405" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Text="*"
ErrorMessage="A file to upload is required"
Display="Dynamic"
ControlToValidate="fuFilename"
ValidationGroup="DocumentUpload"
runat="server" />
</td>
</tr>
<tr>
<td class="label" style="text-align:right;">Document Description:</td>
<td class="normal">
<asp:TextBox ID="txtDescription" runat="server" Width="405" MaxLength="50" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" Text="*"
ErrorMessage="Document Description is a required field"
Display="Dynamic"
ControlToValidate="txtDescription"
ValidationGroup="DocumentUpload"
runat="server" />
</td>
</tr>
<tr>
<td class="label" style="text-align:right;">Document Type:</td>
<td class="normal">
<asp:DropDownList ID="ddDocType" runat="server" Width="405"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Text="*"
ErrorMessage="Document Type is a required field"
Display="Dynamic"
ControlToValidate="ddDocType"
ValidationGroup="DocumentUpload"
runat="server" />
</td>
</tr>
<tr>
<td class="label" style="vertical-align:top;text-align:right;">Customer Types:</td>
<td class="normal">
<asp:Label ID="lblSingleCustomer" Text="Specific Code:" runat="server" /><asp:TextBox ID="txtSingleCustomer" runat="server" Width="100px" /><br />
<asp:CheckBoxList ID="cblCustomerTypes" runat="server" Width="405px" RepeatDirection="Horizontal" RepeatColumns="5" RepeatLayout="Table" CellPadding="10" CellSpacing="0" />
</td>
</tr>
<tr>
<td class="normal" colspan="2"> </td>
</tr>
<tr>
<td class="normal" colspan="2"><asp:Label ID="lblError" runat="server" Text="" ForeColor="Red"/></td>
</tr>
<tr>
<td class="normal" colspan="2">
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="BtnCancel_Click" CssClass="medium" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="BtnUpload_Click" CssClass="medium" />
</td>
</tr>
</table>
</asp:Content>
It USED to work fine, but now, and without apparent change to code/design, both the "Upload" and "Cancel" buttons no longer work.
Putting a breakpoint in the codebehind's Page_Load() method shows that it is only called when the page is initially loaded, and not when the button is pressed.
Similarly, putting a breakpoint in the "BtnUpload_Click" event shows it is never called.
This is now not working both on my own development machine AND on the client's server (both when browsing to the servers page from my machine AND from the server itself).
It's important to stress that, between this working and it now not working, I am 90% sure nothing has changed in regards to the code.
Any help would be greatly appreciated, as the customer is rightly anxious - and i'm clueless as to what's causing it!
EDIT #1
Here's the codebehind for one of the buttons:
protected void BtnUpload_Click(object sender, EventArgs e)
{
if (DataAccess.CheckIfMassUploadAlreadyExists(fuFilename.FileName))
{
lblError.Text = "A file with the specified name already exists within the system.";
return;
}
else
{
try
{
UploadFile();
}
catch(Exception ex)
{
lblError.Text = ex.Message;// +"\nUsername:" + System.Web.HttpContext.Current.User.Identity.Name;
return;
}
}
}
.
Here's the reason.. and it's a really annoying reason too!
THIS:
<script type="text/javascript" src="../Help/HelpPopup.js" />
Should be THIS:
<script type="text/javascript" src="../Help/HelpPopup.js"></script>
Whoever decided the script tag needs to be treated differently to every other HTML tag, needs to be locked in a room with Justin Bieber.
First off all you should check your Validators and perhabs, comment them out for a test.
Is it possible that there are JavaScript-Errors showing on your page?
An ASP-Button is calling a JavaScript-Funktion (WebForm_DoPostBackWithOptions), if there is a JavaScript-Error "before" this line, sometimes you can't press a button.
apparently a client side "return false" is preventing the callback, this could be one of two reasons:
1-the validators always return not valid
2-some client script being called on the button returns false;
At the risk of being down voted for posting an answer to the title question which does not appear to be the OP's problem... I will offer this suggestion which fixed my similar problem:
<body background="images/GlobeBg.png" bgproperties="fixed">
</body>
Problem is, 'bgproperties' is NOT a valid attribute name even though some guys on the internet said it was. Other than an unnoticed squiggle underline in VWD 2008 Express, no error was emitted and the page otherwise looked normal. Simply, the update button and other input controls didn't work.
The cause for this for me was that a validator on another view in the same page was being fired, due to it being apart of the same validation group.So this prevented the post back.

Allow Enter key to login in asp.net?

I have a standard asp:login control:
<asp:Login ID="mbLogin" runat="server" TitleText=""
DestinationPageUrl="~/Default.aspx"
PasswordRecoveryText="Forgot your password?"
PasswordRecoveryUrl="~/LostPassword.aspx"></asp:Login>
In Internet Explorer, pressing Enter does not submit the form, but IE beeps at me 10 times rapidly. In other browsers Enter works perfectly fine and submits the forum as you'd expect.
I've seen this question but that only works when you have actual form element with an actual button, not the login control as a whole.
Why is it being blocked in IE (and why 10 times for some reason)? Is there a workaround?
In the designer of your Login control: "Convert To Template". Then in the Page Load set the defaultButton of your form by finding the LoginButton.
ASPX:
<form id="form1" runat="server">
<div>
<asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
<LayoutTemplate>
<table border="0" cellpadding="1" cellspacing="0" style="border-collapse: collapse;">
<tr>
<td>
<table border="0" cellpadding="0">
.....
<tr>
<td align="right" colspan="2">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
</div>
</form>
Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
Button lbButton = Login1.FindControl("LoginButton") as Button;
form1.DefaultButton = lbButton.UniqueID;
}
This is a hack, but it will provide a work around for your issue with Internet Explorer.
Add a text box to your page that is hidden from view.
<!-- Hack for Internet Explorer browsers to allow the page to post back when the enter key is pressed-->
<asp:TextBox ID="txtIEHackBox" runat="server" style="visibility: hidden; display: none;" />
This will cause Internet Explorer to send back the Button Web control's name/value pair upon hitting Enter.
Button lbButton = Login1.FindControl("LoginButton") as Button;
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
contentPlaceHolder.Page.Form.DefaultButton = lbButton.UniqueID;
I know this is a super old post, but another way to do this is by using an asp:Panel with DefaultButton set to the ID of the button that the user would normally click on to log in:
<asp:Login ID="LoginUser" runat="server">
<LayoutTemplate>
<asp:Panel ID="LoginPanel" runat="server" DefaultButton="LoginButton">
<other stuff here like username and password textboxes>
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In"/>
</asp:Panel>
</LayoutTemplate>

Categories