How to run typing commands when a user sets focus to a text field in a website using C #
I have a user text box and a password text box on a web page.
I want the username textbox to read the following code after it has lost focus or when the user clicks on the password textbox? so the password is automatically displayed in the password text box.
String cookiename = usernameTextBox.Text;
//grab cookie
HttpCookie cookie = Request.Cookies[cookiename];
//exists?
if (null == cookie)
{
Label1.Text = "cookie not found";
}
else
{
passwordTextBox.Attributes.Add("value", cookie.Value.ToString());
}
Focus is the only thing that is available to me, I know it, but I cannot understand it.
thanks,
a source to share
Two problems here:
One, why are you storing the user's password in plain text in the cookie? This is extremely dangerous! This is so fundamentally insecure that you might not have passwords either . There are many ways to handle this. Here's a simple example:
If you want the site to "remember" the user's password, generate a unique token (such as a GUID) and store the GUID along with the account information on the server as an "active session" and store the GUID in a cookie. When the user visits the site, check if the token cookie exists, and if so, you can match that with the user's login information to the server and bypass the login page entirely. There are additional things to consider, but this is the basic concept.
Two, your current design requires an AJAX-like callback. The code you wrote in C # is running on the server, but focus / blur events are happening on the client side.
From a purely technical point of view, you have to write JavaScript to handle this entire process. JS function can run onblur()
, and JS can read cookies just like .NET can:
var usernameBox = document.getElementById('usernameBox');
usernameBox.onblur = handleBlur;
function handleBlur() {
var passwordBox = document.getElementById('passwordBox');
passwordBox.value = readCookie(cookieName);
}
function readCookie(cookieName) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return "";
}
(Note that it getElementById
uses a Client ID , not an ASP.NET ID)
Your security issue is a much bigger issue. There is no way to fix what you are trying to accomplish; it's just a fundamentally bad idea.
a source to share