I'm trying to encrypt the textbox when it sends, what I'm trying to do is get the text encrypt and return the encrypted test to the textbox when the button is pressed, this is the code:
the javascript
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
--all the textbox is here
<asp:Button ID="btnSave" runat="server" CssClass="button" Text="Submit" OnClick="btnSave_Click"></asp:Button>
<script src="../Scripts/jquery-1.10.2.js" ></script>
<script type="text/javascript" language="javascript">
function encrypt(old,new,confirm)
{
if (document.getElementById("<%=txtOldPassword.ClientID%>").value != "")
{
document.getElementById("<%=txtOldPassword.ClientID%>").value = old;
}
if (document.getElementById("<%=txtNewPassword.ClientID%>").value != "")
{
document.getElementById("<%=txtNewPassword.ClientID%>").value = new;
}
if (document.getElementById("<%=txtNewPwdConfirm.ClientID%>").value != "")
{
document.getElementById("<%=txtNewPwdConfirm.ClientID%>").value = confirm;
}
alert("TextBox Value is " + txtOldPassword.value);
}
</script>
</asp:Content>
my javascript inside the asp:content, this is my backend code
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Attributes.Add("OnClientClick", "javascript:return encrypt('" + old() + "','" + newpass() + "','" + conf() + "');");
}
private string old()
{
string old = Encrypt(txtOldPassword.Text);
return old;
}
private string newpass()
{
string newpass = Encrypt(txtNewPassword.Text);
return newpass;
}
private string conf() {
string conf = Encrypt(txtNewPwdConfirm.Text);
return conf;
}
why when I try to click the save button the textbox is not encrypted, I try to call the javascript it seems that asp: content does not detect javascript.
Related
I'm using the javascript from the answer in this question in a project of mine:
Adding Hyperlinks to ValidationSummary
It works really great. I've added it to the bottom of my masterpage (for some reason, even though it is inside $(document).ready, Page_Validators is null if i place it in the head section)
Anyway! I'm also adding some custom validators programatically on postback using this code:
public static CustomValidator ReturnErrorMessage(string message, string validationGroup, string controlToValidate = "")
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ErrorMessage = message;
control.ControlToValidate = controlToValidate;
return control;
}
However whenever I add a CustomValidator like that, in a button event, page_load or whatever, Page_Validators will be overridden and the errormessage will revert to the message without a anchor.
What gives? Am I doing something wrong or can someone explain what is happening?
I've tried debugging it and it does set the values correctly, but then it just reset afterwards.
I've tried for the heck of it and in $(document).ready set all validators as isvalid = false, and that gets overwritten too.
Im using asp.net 4.5 unobtrusive validation, but it does not make a difference if I turn it off.
Adding the javascript in code using Page.ClientScript.RegisterStartupScript at some point after the validator has been created does not work either.
If I don't add any validators in code everything works as expected.
I'm aware I can just add the anchor tags manually, but this is a lot of work to update existing validators instead of just tossing in a small script, so I'm hoping to get this to work.
You can use this code to test this:
using System;
using System.Web.UI.WebControls;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + txtName.ClientID;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = "errorGroup";
control.ErrorMessage = "Error message";
control.ControlToValidate = txtName.ClientID;
Form.Controls.Add(control);
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="vsSummary" runat="server" ValidationGroup="errorGroup" ForeColor="Red" HeaderText="Error!" />
</div>
</form>
<script>
$(document).ready(function() {
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function() {
//get target control and current error validation message from each validator
//[0] is needed when using aspnet 4.5 unobtrusive validation
var validator = $(this)[0];
var errorMsg = validator.errormessage;
var targetControl = validator.controltovalidate;
//make link only if theres a control to target
if (targetControl) {
var errorMsgWithLink = "<a href='#" + targetControl + "' style='color: #FF3232;'> " + errorMsg + "</a>";
//update error message with anchor tag
validator.errormessage = errorMsgWithLink;
}
});
});
</script>
</body>
</html>
If you want you can try implementing your own 'CustomValidationSummary' control by following the same design pattern as mentioned at Reference Source by Microsoft, and modify the render method to include anchor tag to wrap error text, before it is passed into the writer method at line number 462.
I ended up using a extension method, adding the anchor tag in the method
public static void AddValidator(this Page p, string message, string validationGroup, string controlToValidate = "", bool addAnchorTags = true)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ControlToValidate = controlToValidate;
if (addAnchorTags && !string.IsNullOrEmpty(controlToValidate))
{
control.ErrorMessage = "<a href='#" + controlToValidate + "' style='color: #FF3232;'> " + message + "</a>";
}
else
{
control.ErrorMessage = message;
}
p.Validators.Add(control);
}
Please help! i have been trying to call this function on my Asp.net textbox to format users input while typing.
function format(number) {
var decimalSeparator = ".";
var thousandSeparator = ",";
var result = String(number);
var parts = result.split(decimalSeparator);
if (!parts[1]) {
parts[1] = "00";
}
result = parts[0].split("").reverse().join("");
result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);
parts[0] = result.split("").reverse().join("");
return parts.join(decimalSeparator);
}
// i tried using onkeyup, it didnt work
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onKeyup="javaScript: format(this);"></asp:TextBox>
// also i tried using onChange, it didnt work.
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onChange="javaScript:format(this);"></asp:TextBox>
protected void Page_Load(object sender, EventArgs e)
{
txtTransport.Attributes.Add("onKeyup", "javaScript: format(this);");
}
You can do it directly from javascript, not in codebehind !
var el = document.getElementById("<%= txtTransport.ClientID %>");
el.onkeyup = function(e) {
// Do stuff
};
But I think your function is logicaly wrong. Try it anyway. Your ID of a server side control is not exactly the same you write in the code, for get the real ID you can use <%= txtTransport.ClientID %>.
There is a span element that need to load data dynamically from a Repeater control.
The problem that I encounter is only first span element can display the value. The subsequent will display blank.
I've simplify the code behind as below.
private int incre = 0;
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem ritem in FeaturedRepeater.Items)
{
HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
span.Load += new EventHandler(test);
}
}
protected void test(object sender, EventArgs e)
{
HtmlGenericControl span = (HtmlGenericControl)sender;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
incre++;
}
Javascript function in .aspx file example as below:
function timer(increment, timespan) {
var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
document.getElementById(id).innerHTML = id;
}
HTML part:
<asp:Repeater runat="server" ID="FeaturedRepeater" OnItemDataBound="FeaturedRepeater_ItemDataBound">
<ItemTemplate>
<span id='countdown' runat="server"></span>
</ItemTemplate>
</asp:Repeater>
Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);
you can't register the same key more then one time.
that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work
btw
and ; after every javascript function call.
Before getting in details, I would like to mention I've tried various solutions from stackoverflow and net too. But, none suitable in my scenario. So, I provided detailed information.
In an ASP.NET 2.0 Web Application, a gridview controls is used and columns of that gridview are generated at runtime with respect to user's settings.
So, in Default.aspx the gridview definition is as below:
<div id="DivListB" runat="server" onscroll="SaveScrollValue(); SetListFloatingHeader()" visible="True">
<asp:GridView ID="ObjList" runat="server" OnLoad="ReloadGrid" CssClass="ObjList" AutoGenerateColumns="false" OnRowDataBound="ObjList_RowDataBound" AutoGenerateSelectButton="false" OnSelectedIndexChanged="ObjList_SelectedIndexChanged" OnRowCreated="ObjList_RowCreated">
<Columns>
<asp:TemplateField HeaderText=" " ItemStyle-Width="46px" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:CheckBox AutoPostBack="true" ID="chkAll" runat="server" OnCheckedChanged="HeaderChk_Changed" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox AutoPostBack="true" ID="chkRow" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "Selection")%>' OnCheckedChanged="ChkRow_OnCheckChange" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The gridview columns are added at runtime and below method creates the columns depending upon user settings from web.config:
private void CreateDefaultGridView(Hashtable htPartSchema)
{
string sTempHeader, sTempAlignment, sTempWidth, sTempVisible;
try
{
//get partlist settings section from web.config
NameValueCollection plConfigKeys = (NameValueCollection)ConfigurationManager.GetSection("CONFIG_SETTINGS/PL_SETTINGS");
//cond: check partlist config keys exist
if (plConfigKeys != null && plConfigKeys.Count > 0)
{
//loop: every key present in configruation
foreach (string key in plConfigKeys)
{
//cond: config key is present in part schema
if (htPartSchema.ContainsKey(key.ToUpper()) == true)
{
//create new databound column
BoundField gridCol = new BoundField();
//assign datafield to bind with data table column
gridCol.DataField = key;
//get value from config key
string sKeyValue = plConfigKeys[key].ToString();
try
{
string[] sTempArray = sKeyValue.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
sTempHeader = sTempArray[0];
sTempAlignment = sTempArray[1];
sTempWidth = sTempArray[2];
sTempVisible = sTempArray[3];
PLDefaultColumnHeaderAlignments.Add(sTempHeader, sTempAlignment);
PLDefaultColumHeaderWidths.Add(sTempHeader, sTempWidth);
}
catch
{
sTempHeader = string.Empty;
sTempAlignment = string.Empty;
sTempWidth = string.Empty;
sTempVisible = "false";
}
if (sTempVisible.ToLower().Equals("true"))
{
//assign display header text
gridCol.HeaderText = sTempHeader;
//add the column in the gridview
ObjList.Columns.Add(gridCol);
//cond: to check the specified alignment
if (sTempAlignment.ToUpper() == "L")
{
gridCol.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
gridCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
}
else if (sTempAlignment.ToUpper() == "R")
{
gridCol.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
gridCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
}
else if (sTempAlignment.ToUpper() == "C")
{
gridCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
gridCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
}
if (string.IsNullOrEmpty(sTempWidth) == false)
{
gridCol.ControlStyle.Width = Unit.Pixel(int.Parse(sTempWidth));
gridCol.HeaderStyle.Width = int.Parse(sTempWidth);
gridCol.HeaderStyle.Wrap = false;
gridCol.ItemStyle.Wrap = false;
gridCol.ItemStyle.Width = Unit.Pixel(int.Parse(sTempWidth));
//set column width
double dTempColWidth = 120; //default value
double.TryParse(sTempWidth, out dTempColWidth);
//change width of grid view according to column sizes
ObjList.Width = new Unit((ObjList.Width.Value + dTempColWidth), UnitType.Pixel);
}
}
gridCol.ItemStyle.Wrap = false;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
And when rows are bounded with GridView few events and css are also applied at runtime in DataRowBound Event of GridView as mentioned below:
protected void ObjList_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
int iDataRowsCounter = 0;
if (e.Row.RowType == DataControlRowType.DataRow)
{
//get datatable from
DataTable dtList = (DataTable)Session["ListTable" + ViewState["ViewerId"]];
//get position of the respective row
string strPostion = dtList.Rows[e.Row.RowIndex]["Position"].ToString();
string strLinkNum = dtList.Rows[e.Row.RowIndex]["LinkNumber"].ToString();
//get row check box
CheckBox cbRow = ((CheckBox)e.Row.FindControl("chkRow"));
string pnum = dtList.Rows[e.Row.RowIndex]["PartNumber"].ToString();
if (a_PartNumber != null && pnum == a_PartNumber)
{
HighlightPic.Value = HighlightPic.Value + "||" + e.Row.RowIndex.ToString();
e.Row.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#3D98FF");
e.Row.Style.Add(HtmlTextWriterStyle.Color, "#FFFFFF");
}
//mouse hover effects on gridview (CSS)
e.Row.Attributes.Add("onmouseover", "this.className='ObjListHighlight'");
e.Row.Attributes.Add("onmouseout", "this.className='ObjListNormal'");
//keep position of the row in case needed in javascript
e.Row.Attributes.Add("RowPosition", strPostion);
//on row checkbox check change of a single row
cbRow.Attributes.Add("onclick", "OnRowCheckChange(this, 'ObjList')");
//on full row click highlight picture
e.Row.Attributes.Add("onclick", "HighlightPicture('" + strPostion + "'," + e.Row.RowIndex + ", false)");
//on row double click
e.Row.Attributes.Add("ondblclick", "OnRowDblClick(" + e.Row.RowIndex + ",'ObjList')");
}
else if (e.Row.RowType == DataControlRowType.Header)
{
//find header checkbox control
CheckBox cbHeader = ((CheckBox)e.Row.FindControl("chkAll"));
e.Row.Attributes.Add("class", "item_HeaderRow");
e.Row.Cells[0].Attributes.Add("class", "item_HeaderCell");
//add header change event on checkbox click
cbHeader.Attributes.Add("onclick", "OnHeaderCheckChange(this,'ObjList')");
}
}
catch
{
throw new Exception(ex.Message);
}
}
Its presentation is something like below:
Respective css is as below:
.ObjList
{
height: auto;
}
.ObjListHighlight
{
background-color: #CAE4FF;
cursor: pointer;
}
.ObjListNormal
{
background-color: White;
cursor: pointer;
}
.ObjList tr.row
{
cursor: pointer;
color: #1B3A7A;
background-color: #FFFFFF;
}
.ObjList tr.row:hover
{
background-color: #CAE4FF;
}
.ObjList tr.row_selected
{
cursor: default;
color: #FFFFFF;
background-color: #3D98FF;
}
What I wanted to do is to fix the header row of that gridview. Solution can be in javascript or jQuery. Suggestions are appreciated.
Try this,
ASPX page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script src="gridviewScroll.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
gridviewScroll();
});
function gridviewScroll() {
gridView1 = $('#gridtest').gridviewScroll({
width: 600,
height: 300,
railcolor: "#F0F0F0",
barcolor: "#CDCDCD",
barhovercolor: "#606060",
bgcolor: "#F0F0F0",
freezesize: 1,
arrowsize: 30,
headerrowcount: 1,
railsize: 16,
barsize: 8
});
}
</script>
<div style="width: 100%; height: 400px; overflow: scroll">
<asp:GridView ID="gridtest" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="ID" SortExpression="UserID" ReadOnly="true" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
</Columns>
</asp:GridView>
</div>
CS page:
protected void Page_Load(object sender, EventArgs e)
{
gridtest.DataSource = getUserDetails();
gridtest.DataBind();
}
public class details
{
public int UserID { get; set; }
public string FirstName {get;set;}
}
public List<details> getUserDetails()
{
List<details> gt = new List<details>();
for (int i = 1; i < 40; i++)
{
details objDetails = new details();
objDetails.UserID = i;
objDetails.FirstName = "test" + i;
gt.Add(objDetails);
}
return gt;
}
For reference use this : http://gridviewscroll.aspcity.idv.tw/
Your best bet would be to create two GridViews. One purely for the header. Second, for the body wrapped in a scrollable div just below the first one. Position the second gridview with a negative top margin to hide its header. This way you will use the header of the first girdview and scroll the second one.
Alternatively, you can use a plugin like this one: http://www.fixedheadertable.com
This plugin also uses the same logic as I described above.
I came across a scenario where i need to store value of Textbox in session variable in OnChange Event of TextBox1 .
How can i store content of x in Session Variable .
//JavaScript
function TextBox1_TextChanged() {
var x = document.getElementById("TextBox1").value;
var SesVar = "'<%= Session["HitCount"] = x %>'";
alert(SesVar);
// HTML
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
onchange="TextBox1_TextChanged()"></asp:TextBox>
Please suggest how to solve the above problem ?
You cannot do that.
As page comes from server , server code is executed first then the client code takes care of the rest.
If you need to do what you intend to do, then in the form create a hidden element with that value and get that element via GET or POST Global variables and store them in session.
<form method="get" action="destination.asp">
<input id="tb1value" name="test" visibility="hidden"></input>
</form>
Once you submit we use javascript(or jquery which is js library) to generally we put the value needed into that hidden value and send to server.
In your case,you just need the textbox to be used directly,form will do the job.
This tutorial might help you
you can not set it directorly.
There are two ways of doing this.
First set AutoPostBack to true
As follows
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server" AutoPostBack='true'
onchange="TextBox1_TextChanged"></asp:TextBox>
and in C# (code behind) on TextBox1_TextChanged write your code to set it in the session
I found solution of my problem.
function TextBox1_TextChanged() {
<%
// c# code to store value runtime in session variable .
Session["HitCount1"] = TextBox1.Text ;
%>
}
<body>
<form id="form1" runat="server">
<div>
<%
// C# code to retrieve session variable value .
string x = null;
x = Session["HitCount1"].ToString().Trim();
if ((x.Equals(null)) || (x.Equals("")))
{
// Session Variable is either empty or null .
TextBox1.Text = "";
}
else
{
TextBox1.Text = Session["HitCount1"].ToString();
}
%>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack='true' onchange="TextBox1_TextChanged()"></asp:TextBox>
</form>
</body>
// I Found another solution using cookie .
// test.aspx code
<script language="javascript" type="text/javascript">
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for (i = 0; i < ca.length; i++)
{
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 '';
}
function restore(){
var sId = readCookie('sessionId');
document.getElementById("TextBox1").value = sId ;
}
function backup() {
var sId = document.getElementById("TextBox1").value;
writeCookie('sessionId', sId, 3);
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
function TextBox1_TextChanged() {
backup();
}
</script>
<body onload="restore()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack="True" onchange="TextBox1_TextChanged()" ></asp:TextBox>
</div>
</form>
</body>
// test.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
Loading();
}
void Loading (){
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}