I have a simple user control which is basically a contact form and consists of three text boxes, 1 button and 1 label. I am also using Telerik RadAjaxLoadingPanel and RadAjaxPanel. The markup of the user control is given below,
<telerik:RadAjaxLoadingPanel ID="RALP_ContactForm" runat="server" Transparency="5">
<div class="border" style="display: table; height: 240px; width: 240px; #position: relative;
overflow: hidden; background-color:White">
<div class="border" style="#position: absolute; #top: 50%; display: table-cell; text-align: center;
vertical-align: middle;">
<div class="border" style="width: 100%; #position: relative; #top: -50%">
<img src="images/cf_animation.GIF" alt="Processing Request..." />
</div>
</div>
</div>
</telerik:RadAjaxLoadingPanel>
<telerik:RadAjaxPanel ID="upContactForm" runat="server">
<div id="form-main">
<div id="form-div">
<p class="name">
<asp:TextBox ID="txtContactName" ValidationGroup="ContactForm" CausesValidation="true"
runat="server" name="name" CssClass="validate[required,custom[onlyLetter],length[0,100]] feedback-input"
ClientIDMode="Static" placeholder="Name"></asp:TextBox>
<asp:CustomValidator ID="customValidator" runat="server" ValidationGroup="ContactForm"
ControlToValidate="txtContactName" Display="Dynamic" ClientValidationFunction="ValidateContactName"
ErrorMessage="" ValidateEmptyText="true"></asp:CustomValidator>
</p>
<p class="email">
<asp:TextBox ID="txtContactEmail" ValidationGroup="ContactForm" CausesValidation="true"
runat="server" name="email" CssClass="validate[required,custom[onlyLetter],length[0,100]] feedback-input"
ClientIDMode="Static" placeholder="Email"></asp:TextBox>
<asp:CustomValidator ID="customValidator1" runat="server" ValidationGroup="ContactForm"
ControlToValidate="txtContactEmail" Display="Dynamic" ClientValidationFunction="ValidateContactEmail"
ErrorMessage="" ValidateEmptyText="true"></asp:CustomValidator>
</p>
<p class="text">
<asp:TextBox ID="txtContactComment" ValidationGroup="ContactForm" CausesValidation="true"
TextMode="MultiLine" runat="server" name="text" ClientIDMode="Static" CssClass="validate[required,custom[onlyLetter],length[0,100]] feedback-input"
placeholder="Comment"></asp:TextBox>
<asp:CustomValidator ID="customValidator2" runat="server" ValidationGroup="ContactForm"
ControlToValidate="txtContactComment" Display="Dynamic" ClientValidationFunction="ValidateContactComment"
ErrorMessage="" ValidateEmptyText="true"></asp:CustomValidator>
</p>
<p><asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label></p>
<div class="submit">
<asp:Button ID="btnSubmitContactForm" Width="100%" runat="server" ValidationGroup="ContactForm"
Text="SEND" CssClass="btn-flat gr btn-submit-reg" OnClick="btnSubmitContactForm_Click" />
</div>
</div>
</div>
On the code behind I am just sending the information from the textboxes to an email address. The code for the event when the submit button is clicked is as follow,
protected void btnSubmitContactForm_Click(object sender, EventArgs e)
{
try
{
string AppPath = Request.PhysicalApplicationPath;
StreamReader sr = new StreamReader(AppPath + "EmailTemplates/UserFeedback.htm");
string MailBody = sr.ReadToEnd();
MailBody = MailBody.Replace("<%Name%>", txtContactName.Text.Trim());
MailBody = MailBody.Replace("<%Email%>", txtContactEmail.Text.Trim());
MailBody = MailBody.Replace("<%Comments%>", txtContactComment.Text.Trim());
// Close the StreamReader after reading text from it
sr.Close();
MailMessage message = new MailMessage(
"sender#mymail.com",
"receiver#mymail.com",
"Feedback",
MailBody);
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.myserver.com";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.Credentials = new NetworkCredential("MyUserName", "MyPassword");
try
{
smtp.Send(message);
}
catch
{
}
txtContactComment.Text = "";
txtContactEmail.Text = "";
txtContactName.Text = "";
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Feedback sent successfully!";
}
catch
{
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Error sending feedback ! ";
}
}
The User control is called like this,
<uc1:FooterContactForm ID="FooterContactForm" runat="server"></uc1:FooterContactForm>
And at the top of the page,
<%# Register Src="ContactForm.ascx" TagName="FooterContactForm" TagPrefix="uc1" %>
Now all this is very simple and works just fine on my test machine. When I publish this in the server then loading image is displayed but code behind is not fired. I have tried to set the dummy text in the label on Page_Load event of the user control but even that test is not displayed on the user control on live server. I am receiving email every time when I submit this locally.
My question is that why the code behind is not called when the user control is published on the live server and is someone else has experienced such issue?
Edit: (Errors found from console)
POST http://test.mywebsite.com/ 500 (Internal Server Error)
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net.XMLHttpExecutor.executeRequest
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net._WebRequestManager.executeRequest
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net.WebRequest.invoke
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._onFormSubmit
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._doPostBackTelerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._doPostBackWithOptions
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
(anonymous function)(index):800
onclick
Second error:
Uncaught Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 Error.create
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._createPageRequestManagerServerError
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:15
Sys.WebForms.PageRequestManager._onFormSubmitCompleted
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 (anonymous function)
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 (anonymous function)
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6
Sys.Net.WebRequest.completed
Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=RadScriptManager1_TSM&compress=1&_TSM_CombinedScri…:6 _onReadyStateChange
When you have something inside an ajax panel, and for some reason starts to not work, then is probably a javascript error that you miss, a file that is not loaded, an exception that you did not see.
In this cases just remove the ajax panel to locate the error on the code, and/or check the javascript console error on the browser.
From your comments sounds that if the user is not authenticated, some javascript files on some folder fail to load because of the security and then you have some javascript errors that not let your code run correctly.
Related
I have a problem on how to get the exact person id with email address to do resetting password. So, from here I will send a hyperlink to the user via email.
SmtpClient client = new SmtpClient();
try
{
SendPasswordResetEmail(u.EmailAddress.ToString(),u.Name.ToString(),UniqueID);
lblMessage.ForeColor = System.Drawing.Color.LimeGreen;
lblMessage.Text = "Email has been successfully sent!";
}
catch (Exception exc)
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "ERROR: " + exc.Message;
}
Then this is my message content to the user in order to let them click into the hyperlink.
string emailAddress = txtEmail.Text;
User u=db.Users.Single(x =>
x.EmailAddress == emailAddress);
MailMessage mailMessage = new MailMessage(u.EmailAddress, ToEmail);
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("Dear " + u.Name.ToString() + ",<br/><br/>");
sbEmailBody.Append("Please click on the following link to reset your password");
sbEmailBody.Append("<br/>"); sbEmailBody.Append("https://localhost:44305/Registration/ChangePwd.aspx?uid=" + u.Id);
sbEmailBody.Append("<br/><br/>");
sbEmailBody.Append("<b>吹水站</b>");
mailMessage.IsBodyHtml = true;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.Subject = "Reset Your Password";
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(txtEmail.Text));
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
Then this is my ChangePwd.aspx?uid= pages
<form id="form1" runat="server">
<div>
<h1>Change password</h1>
</div>
<div>
<asp:Literal ID="litEmailAddress" runat="server"></asp:Literal>
</div>
<div>
<p>Enter new password :
<asp:TextBox ID="txtNewPwd" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please fill in the blank" ControlToValidate="txtNewPwd" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNewPwd" CssClass="error" ErrorMessage="Password must be between 8-16 characters including at least 1 letter and 1 number" ValidationExpression="((?=.*\d)(?=.*[a-z]).{8,16})"></asp:RegularExpressionValidator>
</p>
</div>
<div>
Re-enter new password:
<asp:TextBox ID="txtRepeatPwd" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please fill in the blank" ControlToValidate="txtRepeatPwd" CssClass="error" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtNewPwd" ControlToValidate="txtRepeatPwd" CssClass="error" ErrorMessage="Password and repeat password are not matched"></asp:CompareValidator>
</div>
<p>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="False" PostBackUrl="~/Registration/Login.aspx" /><asp:Button ID="btnConfirm" runat="server" Text="Confirm" OnClick="btnConfirm_Click" />
</p>
<div>
<p><asp:Label ID="lblSuccess" runat="server" Text=""></asp:Label></p>
<asp:Label ID="lblFailed" runat="server" Text=""></asp:Label>
</div>
</form>
From here, I don't know how to get the exact user email address when they clicked the hyperlink to ChangePwd.aspx to do resetting. And then, I have to update the database to store the updated changed password for the user. I tried to search online but lack of resources I got from the internet. Anyone please help thank you.
When the ChangePwd.aspx page is loaded you need to identify the user uniqely so that you can save the new password to that specific user. What you need here is to pass the primary id(either user Id or email address) from your email to the ChangePwd.aspx page. Which you are doing correctly by passing the ID to the Urls query string,
https://localhost:44305/Registration/ChangePwd.aspx?uid=" + u.Id);
Now, You need to read this in your ChangePwd.aspx.cs (the serverside class of the WebForm). You can do something like this in the page_load method,
protected void Page_Load(object sender, EventArgs e)
{
string userId= Request.QueryString["uid"];
// get the user *User* from the database, using the above retrieved ID
litEmailAddress.text = User.email; // something like this
}
Now, you can save the new password to this user. Let me know if this helps or need more help.
You should be able to use the Request.QueryString property to access the value of uid specified in the URL (i.e. Request.QueryString["uid"]). It should then be straightforward to fetch the User object with that Id and get the user's email address.
Here is a basic tutorial: https://www.c-sharpcorner.com/UploadFile/ca2535/query-string-in-Asp-Net/
First, I'm a student, though this is not for school. I'm trying to create a contact us page for my church's website (http://fpcoakwood.azurewebsites.net). I haven't published the contact page yet, as I'm trying to build it. I'm using Bootstrap/jQuery/ASP.NET to build the site. There is a videos page that uses ASP to get the list of videos from YouTube for our channel, and then populates the select html element from that, and I have it working so that selecting a different video loads that video into the player without a postback (though I do wish I could make the back button take me back to the prior page, rather than cycling through prior videos first).
On this page, my challenge is that I'm trying to send an email. I have the code behind working so that I can send the email, but I'm also trying to disable the send button and fadeIn a result div, which would show either success or failure to send the email. The problem is that because the postback occurs, the page reloads, and I lose the disabling of the button and the showing of the status.
Here's some of the code I have so far:
HTML:
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" OnClick="sendMail_Click" OnClientClick="sendMail(); return false;" runat="server" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Success!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later.</div>
JS:
$("#sendMail").click(function (event) {
event.preventDefault();
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").attr("disabled", true);
$("#sendMail").attr("text", "Sending...");
return true;
});
C#:
protected void sendMail_Click(object sender, EventArgs e)
{
//sendMail.Enabled = false;
//sendMail.Text = "Sending...";
SendMessage();
}
If I get rid of the javascript function, I can send the email. It goes through no problems. But with the javascript function, the breakpoint in the C# function is never hit, so it's not hitting the server. What I want is to be able to validate in js before sending to the server, then send to the server without a postback, and have the server send a message to the js allowing either the fail or the success message div to fadeIn().
Any help will be VERY much appreciated. Thanks in advance!
The jquery function runs before the C# code behind and interfere with it's result.
To do what you want you could do all the work on the server-side.
You can use ajax to do that.
Use an updatepanel around the controls and an updateprogress with the "sending..." message. Capture the sendmessage() result and then show the #sendsuccess or #sendFailed according to it.
I ended up using the answer in this post (How to call code behind method from a javascript function?) to do what I wanted to do. Surely it could have been done with Filipe's answer, but at this point, I'm already drinking from a fire hose trying to learn what I can learn, so this was easier for me, since I already have a fair understanding of all of the pieces involved.
Here's my HTML:
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div class="col-md-8 col-md-offset-2" runat="server">
<div class="form-group">
<label for="userName">Your name (requrired):</label>
<input type="text" class="form-control" id="userName" runat="server" />
</div>
<div class="form-group">
<label for="email">Email address (required):</label>
<input type="email" class="form-control" id="email" runat="server" />
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" id="message" rows="5" runat="server"></textarea>
</div>
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" runat="server" OnClientClick="sendMail(); return false;" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Your message has been sent. Thank you for contacting First Pentecostal Church of Oakwood. You are important to us!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later. You are important to us!</div>
</div>
</form>
There is an error in the HTML, as the OnClientClick doesn't find the function, but without it and the return false, the page does a postback. I'm not sure how to fix it, as the preventDefault() in the JS doesn't solve it, and using the UseSubmitBehavior by itself doesn't do it, either. But this works, though it shows as an error in the developer tools in the browser.
Here's the CSS:
#sendSuccess,
#sendFailed {
display:none;
border: 1px solid black;
border-radius: 5px;
padding: 5px;
}
#sendSuccess {
background-color: rgba(147, 197, 75, .7);
}
#sendFailed {
background-color: rgba(201, 48, 44, .7);
}
Here's the JavaScript:
//Set up event handler for send message contact page button
$("#sendMail").click(function (event) {
event.preventDefault();
sendMail();
});
//above is in the $(document).ready function
function sendMail() {
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").prop("value", "Sending...");
$("#sendMail").attr("disabled", true);
var name = $("#userName").val();
var email = $("#email").val();
var msg = $("#message").val();
PageMethods.SendMessage(name, email, msg, onSuccess, onError);
}
function onSuccess(result) {
if (result) {
$("#sendSuccess").fadeIn();
$("#userName").prop("value", "");
$("#email").prop("value", "");
$("#message").prop("value", "");
$("#sendMail").prop("value", "Send Message");
$("#sendMail").attr("disabled", false);
}
else { onError(result); }
}
function onError(result) {
$("#sendFailed").fadeIn();
$("#sendMail").prop("value", "Try Again");
$("#sendMail").attr("disabled", false);
}
And here's the C#:
[System.Web.Services.WebMethod()]
public static bool SendMessage(string user, string email, string msg)
{
string to = "xxxxxxxxx#outlook.com";
string from = "xxxxxxxxxx#outlook.com";
string subject = "Message from OakwoodFPC.org Contact Page";
string body = "From: " + user + "\n";
body += "Email: " + email + "\n";
body += msg;
MailMessage o = new MailMessage(from, to, subject, body);
NetworkCredential cred = new NetworkCredential("xxxxxxxxxx#outlook.com", "password");
SmtpClient smtp = new SmtpClient("smtp.live.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = cred;
try
{
smtp.Send(o);
return true;
}
catch (Exception)
{
return false;
}
}
Am using the below code to assign the label text using javascript. It's working well. But i can't able to read the label text in code behind. Please help me to fix this issue.
Javascript:
==========
var lbl_total = document.getElementById('<%= lbl_total.ClientID %>');
lbl_total.innerHTML = '500';
c# code behid :
===============
string total = lbl_total.Text; //It always return "";
client side changes for label will not get reflected in server side as its data is not posted to server. So the solution is to take an input hidden control and set its value with label's updated value. Below is the sample code:
<script type="text/javascript">
$(document).ready(function() {
var total = 0;
$('#Button1').click(function() {
total += 150;
$("span[id$=lbl_TotalCount]").html(total);
$("input:hidden[id$=MyHidden]").val(total);
});
});
</script>
html
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
<asp:Button ID="btn_saveForm" runat="server" Text="save" CssClass="btnForm" OnClick="btn_saveForm_Click" />
<asp:Label ID="lbl_TotalCount" Style="color: #00e4ff; font-family: Arial; font-weight: bold;
text-decoration: underline" runat="server" Text="0">
</asp:Label>
<asp:HiddenField ID="MyHidden" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
full Article : Get label value in code behind whose text is changed via JavaScript/jQuery
I have a form that calls some javascript and some code behind (C# for me) when a link button is pressed. Normal operation should act as such: Click on link button which gets text from a label on the form, opens an HTML editor, save the text by clicking 'Done' on the text editor and then displaying the text on the form again. It will do all of that, but I get an error (control is undefined) and then that prevents me from doing any other work on the form.
First, here is my aspx code, which is a window that hold the HTML editor, and the HTML editor.
<asp:Panel ID="EditCommentPopup" runat="server" SkinID="PopupPanel" HorizontalAlign="Center" Width="500px" Style="display:none;">
<div id="SendCommentHeader" class="modalPopupHeader">
<table width="100%" style="vertical-align: middle">
<tr>
<td style="width: 50%; text-align: left; padding-left: 5px;">
<asp:Label ID="EditCommentHeaderLBL" runat="server" Font-Bold="true" Text="Change Comment" ></asp:Label>
</td>
<td style="width: 50%; text-align: right; padding-right: 3px;">
<asp:Button SkinID="SubmitButton" ID="SaveComment" runat="server" Text="Done" OnClientClick="submitEditorPopup(); return true;" OnClick="SubmitCommentButton_Click"/>
<asp:Button SkinID="CancelButton" ID="cancelCommentButton" runat="server" Text="Cancel"/>
</td>
</tr>
</table>
</div>
<ajaxToolkit:ModalPopupExtender ID="EditCommentPopupExtender" runat="server" TargetControlID="EditCommentHeaderLBL"
PopupControlID="EditCommentPopup" BackgroundCssClass="modalBackground" PopupDragHandleControlID="EditCommentPopup"
DropShadow="False" CancelControlID="cancelCommentButton" BehaviorID="ChangeCommentsPopup" >
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="EditCommentInnerPanel" SkinID="PopupInnerPanel" HorizontalAlign="Center" runat="server" >
<asp:Label ID="CommandArgLBL" runat="server" Visible="false"></asp:Label>
<custom:CustomTextEditor ID="EditCommentsTextBox" runat="server" Width="100%" Height="300px" NoScript="true" />
</asp:Panel>
</asp:Panel>
Here are my javascript functions
var contentLBL;
var editorControl;
var hiddenField;
function LoadEditorPopup(labelID, editorID, hiddenID, linkID) {
editorControl = document.getElementById(editorID);
contentLBL = document.getElementById(labelID);
hiddenField = document.getElementById(hiddenID);
editorControl.control.set_content(contentLBL.innerHTML);
var popup = $find("ChangeCommentsPopup");
popup.show();
}
function submitEditorPopup() {
var tmp = editorControl.control.get_content(); //error flags here
contentLBL.innerHTML = tmp;
var str= new String();
str = tmp;
str = str.replace(/</g, "{%");
str = str.replace(/>/g, "%}"); //stripping out html tags to prevent sql insertion
hiddenField.value = str;
var popup = $find("ChangeCommentsPopup");
popup.hide();
}
And here are my C# functions
protected void ShowEditCommentPopup(object sender, EventArgs e)
{
string arg = ((LinkButton)sender).CommandArgument;
string content = "";
string title = "";
switch (arg)
{
//doing stuff, setting content and title
}
EditCommentHeaderLBL.Text = title;
CommandArgLBL.Text = arg;
EditCommentsTextBox.Content = content;
EditCommentPopupExtender.Show();
EditModalPopupExtender.Show(); //this is the form
}
So, what's happening here, I click on a linkbutton (not shown in aspx code) and it fires the LoadEditorPopup function in the javascript. It does its stuff and I have a 'return true' in the onclientclick call so that the next function, ShowEditCommentPopup, in the code behind, will be called. The editor pops up and I can use it just fine. When I click 'Done' the SubmitEditorPopup event is fired in the javascript and I get an error saying that the variable EditorControl is undefined. I have found that if I do not call the ShowEditCommentPopup method, the error does not occur, but then I get back to another problem I had originally, which I'm hoping that will be fixed if this problem is fixed.
I really hope that was clear enough. Thanks in advance!
You have a snippet with your javascript functions. Where does that code live? It it inside a class or function that could be getting called a second time? If so, var editorControl; could be getting run again and override your previous editorControl variable. I would put an alert right about var editorControl; to make sure.
alert( 'Should only happen once' );
var editorControl;
Since that didn't help, I guess you could try replacing
var tmp = editorControl.control.get_content();
with
tmp = document.getElementById(editorID);
in submitEditorPopup.
I have a master page that holds the loginview content that appears on all subsequent pages based on the master page. i have a username control also nested in the loginview to display the name of the user when they are logged in. the code for the loginview from the master page is displayed as follows:
<div class="loginView">
<asp:LoginView ID="MasterLoginView" runat="server">
<LoggedInTemplate>
Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" />
<asp:Label ID="userNameLabel" runat="server" Text="Label"></asp:Label></span>!
[ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/Logout.aspx"/> ]
<%--Welcome:
<span class="bold"><asp:LoginName ID="MasterLoginName" runat="server" /> </span>!--%>
</LoggedInTemplate>
<AnonymousTemplate>
Welcome: Guest
[ Log In ]
</AnonymousTemplate>
</asp:LoginView>
<%-- [ <asp:LoginStatus ID="MasterLoginStatus" runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Logout.aspx" /> ] --%>
</div>
Since VS2010 launches with a default login page in the accounts folder, i didnt think it necessary to create a separate log in page, so i just used the same log in page. please find the code for the login control below:
<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false">
<LayoutTemplate>
<span class="failureNotification">
<asp:Literal ID="FailureText" runat="server"></asp:Literal>
</span>
<asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification"
ValidationGroup="LoginUserValidationGroup"/>
<div class="accountInfo">
<fieldset class="login">
<legend style="text-align:left; font-size:1.2em; color:White;">Account Information</legend>
<p style="text-align:left; font-size:1.2em; color:White;">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User ID:</asp:Label>
<asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
CssClass="failureNotification" ErrorMessage="User ID is required." ToolTip="User ID field is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p style="text-align:left; font-size:1.2em; color:White;">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server" CssClass="passwordEntry"
TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p style="text-align:left; font-size:1.2em; color:White;">
<asp:CheckBox ID="RememberMe" runat="server"/>
<asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
</p>
</fieldset>
<p class="submitButton">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In"
ValidationGroup="LoginUserValidationGroup" onclick="LoginButton_Click"/>
</p>
</div>
</LayoutTemplate>
</asp:Login>
I then wrote my own code for authentication since i had my own database. the following displays the code in the login buttons click event.:
public partial class Login : System.Web.UI.Page
{
//create string objects
string userIDStr, pwrdStr;
protected void LoginButton_Click(object sender, EventArgs e)
{
//assign textbox items to string objects
userIDStr = LoginUser.UserName.ToString();
pwrdStr = LoginUser.Password.ToString();
//SQL connection string
string strConn;
strConn = WebConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString"].ConnectionString;
SqlConnection Conn = new SqlConnection(strConn);
//SqlDataSource CSMDataSource = new SqlDataSource();
// CSMDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString"].ToString();
//SQL select statement for comparison
string sqlUserData;
sqlUserData = "SELECT StaffID, StaffPassword, StaffFName, StaffLName, StaffType FROM Staffs";
sqlUserData += " WHERE (StaffID ='" + userIDStr + "')";
sqlUserData += " AND (StaffPassword ='" + pwrdStr + "')";
SqlCommand com = new SqlCommand(sqlUserData, Conn);
SqlDataReader rdr;
string usrdesc;
string lname;
string fname;
string staffname;
try
{
//string CurrentData;
//CurrentData = (string)com.ExecuteScalar();
Conn.Open();
rdr = com.ExecuteReader();
rdr.Read();
usrdesc = (string)rdr["StaffType"];
fname = (string)rdr["StaffFName"];
lname = (string)rdr["StaffLName"];
staffname = lname.ToString() + " " + fname.ToString();
LoginUser.UserName = staffname.ToString();
rdr.Close();
if (usrdesc.ToLower() == "administrator")
{
Response.Redirect("~/CaseAdmin.aspx", false);
}
else if (usrdesc.ToLower() == "manager")
{
Response.Redirect("~/CaseManager.aspx", false);
}
else if (usrdesc.ToLower() == "investigator")
{
Response.Redirect("~/Investigator.aspx", false);
}
else
{
Response.Redirect("~/Default.aspx", false);
}
}
catch(Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
finally
{
Conn.Close();
}
}
My authentication works perfectly and the page gets redirected to the designated destination. However, the login view does not display the users name. i actually cant figure out how to pass the users name that i had picked from the database to the login name control to be displayed.
taking a close look i also noticed the logout text that should be displayed after successful log in does not show. that leaves me wondering if the loggedin template control on the masterpage even fires at all or its still the anonymous template control that keeps displaying.?
How do i get this to work as expected? Please help....
What i know is that Login controls are bound to Fetch data from Membership provider.
But since you are using your own Login System. It can't get login controls to show data.
If you want to allow Login Controls to show data automatically then Use Membership Classes
http://msdn.microsoft.com/en-us/library/tw292whz.aspx
or if you want to have your own Login system Then Create a Custom membership provider by Implementing Abstract Class MembershipProvider. heres a good resource on that
http://www.asp.net/general/videos/how-do-i-create-a-custom-membership-provider
Another way is to update user information Manually on the controls if you don't want to use membership provider..
I just had this same issue come up. Using Forms authentication and a similar setup to the OP.
To resolve this I did the following in my app:
using System.Web.Security;
and then to set the LoginName:
FormsAuthentication.SetAuthCookie(usr.Username, false);
I have the following in my web.config:
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="~/Default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Sorry for responding to an old post but my search for answers led me here until I discovered it for myself...