I have generated an ASP.NET C# website with the visual studio 2013 wizard in order to get the authentication code and add it to my web app.
I have copied all files and everything looks fine except one thing...
the RegisterExternalLogin.cs file gives me an error in my web, but in the generated sample it works and I don't know why.
This is the error:
RegisterExternalLogin.aspx.cs(65,17,65,25): error CS0103: The name 'userName' does not exist in the current context
RegisterExternalLogin.aspx.cs(82,55,82,63): error CS0103: The name 'userName' does not exist in the current context
Here is the RegisterExternalLogin.aspx
<%# Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="RegisterExternalLogin.aspx.cs" Inherits="Account_RegisterExternalLogin" Async="true" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h3>Register with your <%: ProviderName %> account</h3>
<asp:PlaceHolder runat="server">
<div class="form-horizontal">
<h4>Association Form</h4>
<hr />
<asp:ValidationSummary runat="server" ShowModelStateErrors="true" CssClass="text-danger" />
<p class="text-info">
You've authenticated with <strong><%: ProviderName %></strong>. Please enter a user name below for the current site
and click the Log in button.
</p>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="userName" CssClass="col-md-2 control-label">User name</asp:Label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="userName" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="userName"
Display="Dynamic" CssClass="text-danger" ErrorMessage="User name is required" />
<asp:ModelErrorMessage runat="server" ModelStateKey="UserName" CssClass="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" Text="Log in" CssClass="btn btn-default" OnClick="LogIn_Click" />
</div>
</div>
</div>
</asp:PlaceHolder>
</asp:Content>
and RegisterExternalLogin.aspx.cs
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Web;
using QuoteHD;
public partial class Account_RegisterExternalLogin : System.Web.UI.Page
{
protected string ProviderName
{
get { return (string)ViewState["ProviderName"] ?? String.Empty; }
private set { ViewState["ProviderName"] = value; }
}
protected string ProviderAccountKey
{
get { return (string)ViewState["ProviderAccountKey"] ?? String.Empty; }
private set { ViewState["ProviderAccountKey"] = value; }
}
protected void Page_Load()
{
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
Response.Redirect("~/Account/Login");
}
if (!IsPostBack)
{
var manager = new UserManager();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
Response.Redirect("~/Account/Login");
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
Response.Redirect("~/Account/Login");
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
userName.Text = loginInfo.DefaultUserName;
}
}
}
protected void LogIn_Click(object sender, EventArgs e)
{
CreateAndLoginUser();
}
private void CreateAndLoginUser()
{
if (!IsValid)
{
return;
}
var manager = new UserManager();
var user = new ApplicationUser() { UserName = userName.Text };
IdentityResult result = manager.Create(user);
if (result.Succeeded)
{
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
Response.Redirect("~/Account/Login");
return;
}
result = manager.AddLogin(user.Id, loginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
return;
}
}
AddErrors(result);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
I solved the problem...
I had to wrap the entire codebehind in a namespace
QuoteHD.Account
{
}
Related
I have a website and when opening the page, reloading automatically infinite times.
How do I stop the page from reloading automatically infinite times?
This code is doing that reloading , when i commented this code the reloading not reload the page.
but i don't know how fix it .
any advise .
This is the html code
<h1>
Edit Project</h1>
<div id="Div3" class="entryRow">
<div class="title">
<asp:Label ID="Label8" runat="server" Text="Select Developer"></asp:Label>
</div>
<div class="entry">
<asp:DropDownList ID="ddldeveloperForEdit" runat="server" AppendDataBoundItems="true"
DataSourceID="EntityDataSource2" DataTextField="DeveloperName" DataValueField="DeveloperPK">
<asp:ListItem Text="Select Developer" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:EntityDataSource ID="EntityDataSource2" runat="server" ConnectionString="name=MyCBEntities"
DefaultContainerName="MyCBEntities" EntitySetName="Developer" Select="it.[DeveloperPK], it.[DeveloperName]"
OrderBy="it.[DeveloperName]">
</asp:EntityDataSource>
Select Project
<asp:DropDownList ID="ddlProjects" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlProjects_SelectedIndexChanged">
</asp:DropDownList>
//here this control <cc1:CascadingDropDown code when i comment it the reloading not happened, here the issue how fix it
<cc1:CascadingDropDown ID="CascProjects" PromptText="Select Project" PromptValue="0" Enabled="true"
ServiceMethod="GetProjectsListByDeveloper" ServicePath="~/WebServ/MyCBWebService.asmx"
Category="selProject" TargetControlID="ddlProjects" runat="server" ParentControlID="ddldeveloperForEdit">
</cc1:CascadingDropDown>
</div>
<div class="msg">
</div>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDevelopers();
}
else
{
return;
}
}
private void PopulateDevelopers()
{
using (var db = new MyCBEntities())
{
if (ddlDevelopers.Items.Count > 0)
{
ddlDevelopers.ClearSelection();
ddlDevelopers.Items.Clear();
}
var developers = db.Developer.OrderBy(z => z.DeveloperName).ToList();
ddlDevelopers.Items.Add(new ListItem("Select Developer", "0-1"));
foreach (var developer in developers)
{
ddlDevelopers.Items.Add(new ListItem(developer.DeveloperName, developer.DeveloperPK.ToString()));
}
ddlDevelopers.SelectedIndex = 0;
}
}
This is the ServiceMethod="GetProjectsListByDeveloper"
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod]
public CascadingDropDownNameValue[] GetProjectsListByDeveloper(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
MyCBEntities db = new MyCBEntities();
string developerIdStr = "";
if (kv.Count > 0 && kv.ContainsKey("country"))
{
developerIdStr = kv["country"];
}
else if (kv.Count > 0 && kv.ContainsKey("undefined"))
{
developerIdStr = kv["undefined"];
}
int developerId;
int.TryParse(developerIdStr, out developerId);
List<CascadingDropDownNameValue> values =
new List<CascadingDropDownNameValue>();
if (developerId > 0)
{
var projectList = db.DevelopersProject.Where(z => z.DeveloperFK == developerId).ToList();
foreach (var project in projectList)
{
values.Add(new CascadingDropDownNameValue(project.ProjectName, project.DeveloperProjectPK.ToString()));
}
}
return values.ToArray();
}
can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.
I am using asyncupload control of AjaxControlToolkit and I want to check the file to be uploding is already exists or
not on server.
How we can do this?
Please help me out.
<!-- Client side code for control-->
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
<!-- Control Code in aspx-->
<tr>
<td></td>
<td>
<cc1:AsyncFileUpload ID="FileUpload2" Width="265px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red"
ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../../images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:HiddenField ID="hdnField" runat="server" value=""/>
</td>
</tr>
//.CS Code for ayncupload control
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath="C:\Documents\temp.txt"
if(File.Exists(filePath))
{
hdnField.value="1";//Not able to access this value
}
}
Thanks!!
you just need to set your hidden field value at client side script.
See I have made little changes in your server side code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath = "C:\\Documents\\temp.txt";
string hiddenValue = "0";
if (File.Exists(filePath))
{
hiddenValue = "1";
}
//This script will set required value for hidden field.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetHiddenField", String.Format("top.$get('{0}').value = '{1}'", hdnField.ClientID, hiddenValue), true);
}
Make changes in your script location as follow:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
Check if the file exists using the following:-
File.Exists
You can compare based on the filename.
I have a page SendResults.aspx that holds a button and a ListView with ItemTemplate set to a user control (3 labels and 2 textboxes) that gets it's data from a matching object.
On Page_Load I fill the List with data (this works well).
When the button is clicked I want to take the user input in the user-control's textboxes and do something with it.
However I always get the initial value and not the updated one.
Here is the code:
The user-control "MatchControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MatchControl.ascx.cs" Inherits="TotoMondeal.Controls.MatchControl" %>
<div>
<asp:Image ID="Team1FlagImage" runat="server" />
<asp:Label ID="Team1Label" runat="server" Width="150px"></asp:Label>
<asp:TextBox ID="Team1TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px" AutoPostBack="true" OnTextChanged="Team1TextBox_TextChanged"></asp:TextBox>
<asp:Label ID="Colon" runat="server" Font-Size="XX-Large" Text=":"></asp:Label>
<asp:TextBox ID="Team2TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px"></asp:TextBox>
<asp:Label ID="Team2Label" runat="server" Width="150px"></asp:Label>
<asp:Image ID="Team2FlagImage" runat="server" />
</div>
The user-control code-behind:
public partial class MatchControl : System.Web.UI.UserControl
{
public Match Match
{
get
{
object obj = ViewState["Match"];
return (obj == null) ? new Match() : (Match)obj;
}
set
{
ViewState["Match"] = value;
}
}
public string Team1Score
{
get { return Team1TextBox.Text; }
set { Team1TextBox.Text = value; }
}
public string Team2Score
{
get { return Team2TextBox.Text; }
set { Team2TextBox.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Team1Label.Text = Match.Team1Name;
Team2Label.Text = Match.Team2Name;
Team1TextBox.Text = Match.Team1Score.ToString();
Team2TextBox.Text = Match.Team2Score.ToString();
Team1TextBox.Enabled = Match.EnableTextBox;
Team2TextBox.Enabled = Match.EnableTextBox;
Team1FlagImage.ImageUrl = #"~/FlagImages/" +Match.Team1Name + ".png";
Team2FlagImage.ImageUrl = #"~/FlagImages/" + Match.Team2Name + ".png";
}
protected void Team1TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
try
{
Match updatedMatch = new Match()
{
MatchId = Match.MatchId,
MatchDate = Match.MatchDate,
Result = Match.Result,
Team1Name = Match.Team1Name,
Team1Score = Convert.ToInt32(textBox.Text),
Team2Name = Match.Team2Name,
Team2Score = Match.Team2Score,
EnableTextBox = Match.EnableTextBox
};
Match = updatedMatch;
}
catch (Exception ex)
{
throw ex;
}
}
}
The SendResults.aspx:
<%# Page Title="שלח תוצאות" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendResults.aspx.cs" Inherits="TotoMondeal.SendResults" %>
<%# Register TagPrefix="TOTO" TagName="MatchControl" Src="~/Controls/MatchControl.ascx" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<div class="jumbotron">
<asp:ListView ID="TodayMatchesList" runat="server">
<ItemTemplate>
<TOTO:MatchControl ID="MatchControl" Match="<%# Container.DataItem %>" runat="server" />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:Content>
the SendResults code-behind:
public partial class SendResults : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
foreach (Match match in matches)
{
match.EnableTextBox = true;
}
this.TodayMatchesList.DataSource = matches;
this.TodayMatchesList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < TodayMatchesList.Items.Count; i++)
{
MatchControl match = (MatchControl)TodayMatchesList.Items[i].FindControl("MatchControl");
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
}
}
}
The problem is that in this line:
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
I always get the initial value from the database, and not the user updated input.
Please help I'm new at this.
Your List is getting overwritten every time you post back. Add this in Page_Load for SendResults
if ( !Page.IsPostBack )
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
...etc...
}
In addition to checking IsPostBack you need to handle saving your control properties in the ViewState. As suggested here: User control (ascx) and properties
Example from post:
public string Title {
get { return Convert.ToString(ViewState["Title"]); }
set { ViewState["Title"] = value; }
}
You would do this in your control class.
I originally got this working on a ASP.net application (non MVC) but now that I have to change over to MVC I do not know how to adapt my old code. For reference, I am using the stock website you get for the application (needed to be quick and dirty) and I am also sewing in Zurb's Foundation framework. This is also C# based.
Here is the old way that worked:
LOGIN.ASPX
<form id="Login" method="post" runat="server">
<fieldset>
<legend>Please login</legend>
<asp:Label ID="errorLabel" Runat="server" ForeColor=#ff3300></asp:Label><br>
<div class="row">
<div class="large-12 columns">
<label>Domain:</label>
<asp:TextBox ID="txtDomain" Runat="server" placeholder="Human Check: Please type WORKGROUP"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Username:</label>
<asp:TextBox ID=txtUsername Runat="server" ></asp:TextBox>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Password:</label>
<asp:TextBox ID="txtPassword" Runat="server" TextMode=Password></asp:TextBox><br>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<%-- Submit--%>
<asp:Button ID="Button1" Runat="server" Text="Login" OnClick="Login_Click" CssClass="button"></asp:Button>
</div>
<div class="large-6 columns">
<br />
<asp:CheckBox ID=chkPersist Runat="server" /> Remember Me
</div>
</div>
</fieldset>
</form>
Here was the script below (Same Page) that worked.
<script runat="server">
void Login_Click(object sender, EventArgs e)
{
string adPath = "LDAP://DC03/DC=Meowmeow,dc=com"; //Path to your LDAP directory server
Legend_Forms_Manager.LdapAuthentication adAuth = new Legend_Forms_Manager.LdapAuthentication(adPath);
try
{
if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
{
string groups = adAuth.GetGroups();
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text,DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
//Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if(true == isCookiePersistent)
authCookie.Expires = authTicket.Expiration;
//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
//You can redirect now.
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch(Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
</script>
LdapAuthentication.cs
using System;
using System.Text;
using System.Collections;
using System.DirectoryServices;
namespace Legend_Forms_Manager
{
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
public LdapAuthentication(string path)
{
_path = path;
}
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd, AuthenticationTypes.SecureSocketsLayer);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
}
}
I included the following references:
~ System.DirectoryServices
I am having EXTREME difficulty finding anywhere that has any iota of consistency in a tutorial that does not date back to 2008 or so.
If you can please help me... I have everything out here and now it just needs to be translated, I think.
I added the .aspx and .cs from the old to the new, added ADConnectionString to web.config, and added tokens to the .cs and the .aspx to prevent cross-site scripting (it forced me to as per the references). You can now get to the page, fill in the info, but when you click 'Submit' it blanks the page and does nothing. Still need help.