The TextBox with TextMode = "Password" will be empty after assign a value to it's text property.
How can I set predefined password for my password textbox?
Also I want to use this jQuery code for my textbox :
function onclickOfPassword(This) {
if (This.value == 'Password') {
This.value = '';
}
}
function onblurOfPassword(This) {
if (This.value == '') {
This.value = 'Password';
}
}
you can do like this....using jquery .....
by using below function we can show and hide two different inputs. You need set one with ID Password and another with ID PasswordDummy, For clients with no javascript, best to set PasswordDummy to display:none initially.
$(‘input’).each(function()
{
if (this.id == ‘Password’) {
// Handle Password differently – it only gets an onblur, in which it gies invisible and activates the PasswordDummy if it is empty
// if its blank, make it invisible and Dummy visible
if (this.value == ”)
{
$(this).hide();
$(“#PasswordDummy”).show();
}
else
{
$(this).show();
$(“#PasswordDummy”).hide();
}
$(this).blur(function()
{
if (this.value == ”) {
$(this).hide();
$(“#PasswordDummy”).show();
}
else
{
$(this).show();
$(“#PasswordDummy”).hide();
}
});
}
else if (this.id == ‘PasswordDummy’) {
// Handle Password Dummy differently
this.value = $(this).attr(‘title’);
$(this).addClass(‘text-label’);
$(this).focus(function()
{
$(this).hide();
$(“#Password”).show();
$(“#Password”).focus(); });
}
else if ($(this).attr(‘title’) != undefined)
{
if (this.value == ”)
{
this.value = $(this).attr(‘title’);
$(this).addClass(‘text-label’);
}
$(this).focus(function()
{
if (this.value == $(this).attr(‘title’)) {
this.value = ”;
$(this).removeClass(‘text-label’);
}});
$(this).blur(function()
{
if (this.value == ”) {
this.value = $(this).attr(‘title’);
$(this).addClass(‘text-label’);
}});
}
});
Related
I'm using javascript to set the value of a cookie when I open the debugger panel so that if the user has already opened it, it will automatically open when they reload the page.
Here is the javascript:
jQuery(document).ready(function () {
DebuggingPanel.init(jQuery);
DebuggingPanel.GetPanelState();
});
DebuggingPanel.GetPanelState = function () {
jQuery.ajax({
url: "/sitecore modules/DebuggingPanel/DebuggingPanel.asmx/GetPanelState",
type: 'POST',
success: function(data) {
if (data.open === true) {
DebuggingPanel.TogglePanel();
}
}
});
}
DebuggingPanel.TogglePanel = function (changeState) {
var tinyDiv = $('.debuggingPanel.tinyDiv');
if (tinyDiv.text() == '+') {
tinyDiv.text('-');
DebuggingPanel.GetInformation();
DebuggingPanel.panel.slideDown();
interval = setInterval(DebuggingPanel.GetInformation, 5000);
if (changeState) {
DebuggingPanel.SetPanelState("open");
}
} else {
tinyDiv.text('+');
DebuggingPanel.panel.slideUp();
clearInterval(interval);
if (changeState) {
DebuggingPanel.SetPanelState("closed");
}
}
};
tinyDiv.click(function () {
DebuggingPanel.TogglePanel(true);
});
And here are the methods related to the cookie:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
In debugging the cookie looks as though it is getting the value correctly, but the next time I go into GetPanelState(), panelCookie.Value is always "" (not "open" as it should be, or "closed", which would indicate it was set by the toggle).
This happens when I reload the page, and it also happens when I call GetPanelState() at the end of SetPanelState(); panelCookie.Value = "open" in SetPanelState() but then equals "" in GetPanelState()
When you are reading from the Cookie, you need to use the Request instead of the response. So your code will be as follows:
public void SetPanelState(string state)
{
var panelCookie = HttpContext.Current.Response.Cookies["PanelState"];
if (panelCookie == null)
{
panelCookie = new HttpCookie("PanelState") {Value = state};
HttpContext.Current.Response.Cookies.Add(panelCookie);
}
else
{
HttpContext.Current.Response.Cookies["PanelState"].Value = state;
}
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json), WebMethod(EnableSession = true)]
public void GetPanelState()
{
//It is here that you are reading the cookie.
var panelCookie = HttpContext.Current.Request.Cookies["PanelState"];
var data = new PanelState(){open = false};
if (panelCookie == null || panelCookie.Value == null)
{
data.open = false;
}
else if (panelCookie.Value == "open")
{
data.open = true;
}
WriteOut(data);
}
Thanks
I'm trying to implement a form validation with ASP.net and I have tried every solution suggested here but the best one was on aspsnippets.com so far.
My code is like below:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tTitle"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tEMail"/>
<asp:RegularExpressionValidator runat="server" ControlToValidate="tEMail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit"/>
Javascript
<script type="text/javascript">
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
{
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
} return true;
}
function WebForm_OnBlur() {
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
} return false;
}
</script>
The problem is the e-mail field only validates for the regular expression. If I change the order of the validators, it only validates for required expression.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.
Yes, this is indeed the problem. To fix it, you can do the following:
In the WebForm_OnBlur function, loop through the validators associated with the control that lost focus (rather than all the validators on the page), and clear the className property only if all the validators are valid:
function WebForm_OnBlur(control) {
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.className = "error";
return;
}
}
control.className = "";
}
In the onblur attribute of the TextBox controls, pass this as the argument to WebForm_OnBlur:
<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur(this)"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur(this)"/>
In the WebForm_OnSubmit function, call WebForm_OnBlur for each control that has associated validators:
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) === "function" && ValidatorOnSubmit() === false) {
for (var i = 0; i < Page_Validators.length; i++) {
var control = document.getElementById(Page_Validators[i].controltovalidate);
if (Page_Validators[i] === control.Validators[0]) // minor optimization
WebForm_OnBlur(control);
}
return false;
}
return true;
}
In addition to #MichaelLiu, You can make your own validators that inherit from the CustomValidator class and alter the rendering of the validators to make them a little easier to work with.
For example:
Validators.cs
Take notice of how we add a property of CssControlErrorClass. We will use this when applying a class with the invalid input in question.
We also set other properties so you don't have to set them everytime, ClientValidationFunction and ValidateEmptyText.
public class RequiredFieldValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public RequiredFieldValidator()
{
ClientValidationFunction = "validators.required";
ValidateEmptyText = true;
}
public string InitialValue
{
get
{
object o = ViewState["InitialValue"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
ViewState["InitialValue"] = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RequiredFieldValidation validator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null)
{
return true;
}
var result = (!controlValue.Trim().Equals(InitialValue.Trim()));
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if(!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
}
public class RegularExpressionValidator : CustomValidator
{
public string CssControlErrorClass { get; set; }
public string ValidationExpression
{
get
{
object o = ViewState["ValidationExpression"];
return ((o == null) ? String.Empty : (string)o);
}
set
{
try
{
Regex.IsMatch(String.Empty, value);
}
catch (Exception e)
{
throw new HttpException(string.Format("{0} - {1}", "Validator_bad_regex", value), e);
}
ViewState["ValidationExpression"] = value;
}
}
public RegularExpressionValidator()
{
ClientValidationFunction = "validators.regex";
}
protected override void Render(HtmlTextWriter writer)
{
//Have to add attributes BEFORE the beginning tag is written to the stream
writer.AddAttribute("data-errorClass", CssControlErrorClass);
writer.AddAttribute("data-regex", ValidationExpression);
writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
base.Render(writer);
}
protected override bool EvaluateIsValid()
{
//Default implementation of the RegularExpressionFieldvalidator
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null || controlValue.Trim().Length == 0)
{
return true;
}
try
{
Match m = Regex.Match(controlValue, ValidationExpression);
var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length);
//Check to see if validation failed, if it did, add the class to the control to validate
if (!result)
{
var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
//Didn't look into it too much, but the validators fire twice for some reason
if (!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
}
return result;
}
catch
{
return true;
}
}
}
Validators.js
Since in the previous classes we pre-defined the javascript functions, we can add a simple script like so:
var v = window.validators = window.validators || {
errorControlAttributeName: "data-for",
errorClassAttributeName: "data-errorClass",
regexAttributeName: "data-regex",
required: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
input = document.getElementById(controlId);
var isValid = (args.Value !== "");
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
regex: function(src, args) {
var controlId = src.getAttribute(v.errorControlAttributeName),
errorClass = src.getAttribute(v.errorClassAttributeName),
regexString = src.getAttribute(v.regexAttributeName),
input = document.getElementById(controlId),
regex = new RegExp(regexString);
var isValid = regex.test(args.Value);
v._toggleInputErrorState(input, errorClass, isValid);
args.IsValid = isValid;
return;
},
/************* Helper functions ***********/
_toggleInputErrorState: function (inputEl, errorClass, isValid) {
if (!isValid) {
if (!v._hasClass(inputEl, errorClass)) {
inputEl.className += " " + errorClass;
}
} else {
if (v._hasClass(inputEl, errorClass)) {
//Not the most performant, but is sure is easiest
inputEl.className = inputEl.className.replace(" " + errorClass, "");
}
}
},
_hasClass: function(el, className) {
return el.className.indexOf(className) != -1 ? true : false;
},
}
Very simple validation library that you can easily extend with things you are actually interesting in.
Default.aspx
After than you can put the controls into your page:
<Validators:RequiredFieldValidator runat="server" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED BRO!"></Validators:RequiredFieldValidator>
<Validators:RegularExpressionValidator runat="server" ValidationExpression="[0-9]" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED RegEx BRO!"></Validators:RegularExpressionValidator>
Is this the best way? Probably not, (these two use the default implementation that is given by Microsoft) there are way smarter people out there than I and I don't work with WebForms much. The biggest benefit I see is that you get some reusable code, using a familiar syntax, that will eventually contain all your validation needs versus messing around with js everytime to get the validation "rules" how you want them.
The issue is resolved by replacing the code snippet below. To correct we must loop through all the validators for a control, then we should decide whether it has to marked with the error class. After this, your code will work as expected.
Replace the loop
for (var i in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[i].controltovalidate);
if (!Page_Validators[i].isvalid) {
control.className = "error";
} else {
control.className = "";
}
} catch (e) { }
}
with the below code
for (var j in Page_Validators) {
try {
var control =
document.getElementById(Page_Validators[j].controltovalidate);
var IsError = false;
for (var i in control.Validators) {
if (!control.Validators[i].isvalid) {
IsError = true;
}
}
if (IsError)
control.className = "error";
else
control.className = "";
} catch (e) { }
}
I just ran it and this is working excellently :) Try this solution!
you can try Page_ClientValidate() in javascript instead of looping across validator.
I believe this will validate all the validators on the page.
It also takes in parameter which "Validation group name" if you want to validate specific controls bound by particular validation group.
i want to display error message without alert box by using javascript.
i have tried with code.
function validatetextbox() {
var txtuname = document.getElementById('<%=txt_uname.ClientID %>').value;
if(txtuname=="") {
document.getElementById("text_uname").innerHTML= "Enter Username"; } }
but it is not working, please give some suggestions
You need to use document.getElementById('<%=txt_uname.ClientID %>') instead of document.getElementById("text_uname")
Complete function
function validatetextbox() {
var txtuname = document.getElementById('<%=txt_uname.ClientID %>').value;
if (txtuname == "") {
document.getElementById('<%=txt_uname.ClientID %>').innerHTML = "Enter Username";
}
}
try to cache dom, and set innerHTML
function validatetextbox() {
var inputEl = document.getElementById('<%=txt_uname.ClientID %>'),
txtuname = inputEl.value;
if ( txtuname == "" ) {
inputEl.innerHTML = "Enter Username";
}
}
It seems like you need to show alert in txt_uname .. then you should do like this:
function test(){
var txtuname =document.getElementById('<%=txt_uname.ClientID %>').value;
if(txtuname == "") {
document.getElementById('<%=txt_uname.ClientID %>').value= "Enter Username";
}
}
try this
function test()
{
var row = lnk.parentNode.parentNode;
var txtuname= row.cells[your cell number].childNodes[your node number].innerHTML;
if(txtuname=="")
{
txtuname="enter username";
}
}
I've created a custom BoundField for use with a DetailsView in Edit and Insert modes to utilize Twitter Bootstrap.
The control works fine, except when I add in extra LiteralControls to surround the TextBox with some HTML during InitializeDataCell(...). Code related to this toward the end.
The HTML generated is below seems to be identical to what is generated with a TemplateField. But when I fire an Update, anytime it adds the extra div / span seen here, the value in the TextBox is blank upon PostBack.
<div class="input-prepend">
<span class="add-on">$</span>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</div>
Here is some examples of what I'm doing within the front ASP.NET code and what HTML is generated.
Doesn't work - custom field
Value inside text box is unset after submitting via Update command, ONLY when I add the input-append and add-on part.
Field inside DetailsView
<my:ValidationField DataField="Price" HeaderText="Price" TextPrepend="$" />
HTML generated
<td>
<div class="input-prepend">
<span class="add-on">$</span>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</div>
</td>
Does work - normal TemplateField
Works fine
Field inside DetailsView
<asp:TemplateField>
<EditItemTemplate>
<div class="input-prepend">
<span class="add-on">$</span>
<asp:TextBox ID="tbCost" runat="server" Text='<%# Bind("Cost") %>'></asp:TextBox>
</div>
</EditItemTemplate>
</asp:TemplateField>
HTML generated - identical to what is above
<td>
<div class="input-prepend">
<span class="add-on">$</span>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</div>
</td>
Does work - HTML generated with custom field
Value inside text box is correctly submitted via Update command when I don't add the TextPrepend field.
Field inside DetailsView
<my:ValidationField DataField="Price" HeaderText="Price" />
HTML generated without extra span / div
<td>
<input name="ctl00$ctl00$MainContent$MainContent$pi$dvPackage$tbPrice" type="text" value="0" size="5" id="MainContent_MainContent_pi_dvPackage_tbPrice" title="Price">
</td>
InitializeDataCell parts related to this code creation
I believe this is due to something with the InitializeDataCell(...) implementation.
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
base.InitializeDataCell(cell, rowState);
// Find the text box to validate
TextBox text = FindTextBox(cell);
if (text != null)
{
text.ID = "tb" + DataField;
text.MaxLength = MaxLength;
text.TextMode = TextMode;
text.Text = DataField;
string cellCss = string.Empty;
bool prepend = !string.IsNullOrEmpty(this.TextPrepend);
bool append = !string.IsNullOrEmpty(this.TextAppend);
bool addon = prepend || append;
if (prepend == true)
cellCss = this.ConcatenateCss(cellCss, "input-prepend");
if (append == true)
cellCss = this.ConcatenateCss(cellCss, "input-append");
if (addon == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal container = new Literal();
container.Text = "<div class=\"" + cellCss + "\">";
cell.Controls.AddAt(textIndex, container);
}
if (prepend == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Prepend() + "</span>";
cell.Controls.AddAt(textIndex, units);
}
if (append == true)
{
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Append() + "</span>";
cell.Controls.Add(units);
}
if (addon == true)
{
Literal container = new Literal();
container.Text = "</div>";
cell.Controls.Add(container);
}
}
}
Entire code in case it's useful to anyone trying to use Twitter Bootstrap, or if my code is wrong elsewhere.
public class ValidationField : BoundField
{
#region Properties
public virtual string EditTextCssClass
{
get
{
return (string)(ViewState["EditTextCssClass"] ?? string.Empty);
}
set
{
ViewState["EditTextCssClass"] = value;
OnFieldChanged();
}
}
public virtual ValidatorDisplay ErrorDisplay
{
get
{
return (ValidatorDisplay)(ViewState["ErrorDisplay"] ?? ValidatorDisplay.Dynamic);
}
set
{
ViewState["ErrorDisplay"] = value;
OnFieldChanged();
}
}
public virtual string ErrorMessage
{
get
{
return (string)(ViewState["ErrorMessage"] ?? "Invalid value entered");
}
set
{
ViewState["ErrorMessage"] = value;
OnFieldChanged();
}
}
public virtual string HelpText
{
get
{
return (string)(ViewState["HelpText"] ?? string.Empty);
}
set
{
ViewState["HelpText"] = value;
OnFieldChanged();
}
}
public virtual TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode HelpDisplay
{
get
{
return (TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode)(ViewState["HelpDisplay"] ?? TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode.Block);
}
set
{
ViewState["HelpDisplay"] = value;
OnFieldChanged();
}
}
public virtual int MaxLength
{
get
{
return (int)(ViewState["MaxLength"] ?? 0);
}
set
{
ViewState["MaxLength"] = value;
OnFieldChanged();
}
}
public virtual string PlaceHolder
{
get
{
return (string)(ViewState["PlaceHolder"] ?? string.Empty);
}
set
{
ViewState["PlaceHolder"] = value;
OnFieldChanged();
}
}
public virtual bool Required
{
get
{
return (bool)(ViewState["Required"] ?? false);
}
set
{
ViewState["Required"] = value;
OnFieldChanged();
}
}
public virtual TextBoxMode TextMode
{
get
{
return (TextBoxMode)(ViewState["TextMode"] ?? TextBoxMode.SingleLine);
}
set
{
ViewState["TextMode"] = value;
OnFieldChanged();
}
}
public virtual string ValidationExpression
{
get
{
return (string)(ViewState["ValidationExpression"] ?? string.Empty);
}
set
{
ViewState["ValidationExpression"] = value;
OnFieldChanged();
}
}
public virtual string ValidationGroup
{
get
{
return (string)(ViewState["ValidationGroup"] ?? string.Empty);
}
set
{
ViewState["ValidationGroup"] = value;
OnFieldChanged();
}
}
public virtual string TextAppend
{
get
{
object value = ViewState["TextAppend"];
if (value != null)
return value.ToString();
return string.Empty;
}
set
{
ViewState["TextAppend"] = value;
OnFieldChanged();
}
}
public virtual string TextPrepend
{
get
{
object value = ViewState["TextPrepend"];
if (value != null)
return value.ToString();
return string.Empty;
}
set
{
ViewState["TextPrepend"] = value;
OnFieldChanged();
}
}
#endregion
public ValidationField()
{
}
protected override DataControlField CreateField()
{
return new ValidationField();
}
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
base.InitializeDataCell(cell, rowState);
// Find the text box to validate
TextBox text = FindTextBox(cell);
if (text != null)
{
text.ID = "tb" + DataField;
text.MaxLength = MaxLength;
text.TextMode = TextMode;
text.CssClass = EditTextCssClass;
text.Text = DataField;
if (PlaceHolder != string.Empty)
text.Attributes.Add("placeholder", PlaceHolder);
string cellCss = string.Empty;
bool prepend = !string.IsNullOrEmpty(this.TextPrepend);
bool append = !string.IsNullOrEmpty(this.TextAppend);
bool addon = prepend || append;
if (prepend == true)
cellCss = this.ConcatenateCss(cellCss, "input-prepend");
if (append == true)
cellCss = this.ConcatenateCss(cellCss, "input-append");
if (addon == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal container = new Literal();
container.Text = "<div class=\"" + cellCss + "\">";
cell.Controls.AddAt(textIndex, container);
}
if (prepend == true)
{
int textIndex = cell.Controls.IndexOf(text);
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Prepend() + "</span>";
cell.Controls.AddAt(textIndex, units);
}
if (append == true)
{
Literal units = new Literal();
units.Text = "<span class=\"add-on\">" + this.Append() + "</span>";
cell.Controls.Add(units);
}
if (addon == true)
{
Literal container = new Literal();
container.Text = "</div>";
cell.Controls.Add(container);
}
if (Required == true)
{
Literal required = new Literal();
required.Text = "<span class=\"required\">*</span>";
cell.Controls.Add(required);
}
if (HelpText != string.Empty)
{
Label lblHelpText = new Label();
if (HelpDisplay == TwitterBootstrap.WebControls.TextBox.HelpTextDisplayMode.Block)
lblHelpText.CssClass = "help-block";
else
lblHelpText.CssClass = "help-inline";
lblHelpText.Text = HelpText;
cell.Controls.Add(lblHelpText);
}
if (Required == true)
{
// Add a RequiredFieldValidator
RequiredFieldValidator required = new RequiredFieldValidator();
required.ErrorMessage = ErrorMessage;
required.Display = ErrorDisplay;
required.ControlToValidate = text.ID;
required.Text = "";
if (ValidationGroup != string.Empty)
required.ValidationGroup = ValidationGroup;
cell.Controls.Add(required);
}
if (ValidationExpression != string.Empty)
{
// Add a RequiredFieldValidator
RegularExpressionValidator regex = new RegularExpressionValidator();
regex.ErrorMessage = ErrorMessage;
regex.Display = ErrorDisplay;
regex.ControlToValidate = text.ID;
regex.ValidationExpression = ValidationExpression;
if (ValidationGroup != string.Empty)
regex.ValidationGroup = ValidationGroup;
cell.Controls.Add(regex);
}
}
}
#region Methods
private string ConcatenateCss(params string[] classes)
{
string result = string.Empty;
foreach (string s in classes)
result += s + " ";
return result.TrimEnd().TrimStart();
}
private static TextBox FindTextBox(Control parent)
{
TextBox result = null;
foreach (Control control in parent.Controls)
{
if (control is TextBox)
{
result = control as TextBox;
break;
}
}
return result;
}
protected virtual string Prepend()
{
return this.TextPrepend;
}
protected virtual string Append()
{
return this.TextAppend;
}
#endregion
}
I managed to figure out why this was happening. Since the Control collection was altered in the field, you must also override _ExtractValuesFromCell(...)to get theTextBox` value.
I have used a slightly altered implementation from ASP.NET Boundfield overridden to support Dropdownlist is missing one final feature and haven't optimized for my use case. However, it works fine now.
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
Control control = null;
string dataField = DataField;
object text = null;
string nullDisplayText = NullDisplayText;
if (((rowState & DataControlRowState.Insert) == DataControlRowState.Normal) || InsertVisible)
{
if (cell.Controls.Count > 0)
{
foreach (Control c in cell.Controls)
{
control = cell.Controls[0];
if (c is TextBox)
{
text = ((TextBox)c).Text;
}
}
}
else if (includeReadOnly)
{
string s = cell.Text;
if (s == " ")
{
text = string.Empty;
}
else if (SupportsHtmlEncode && HtmlEncode)
{
text = HttpUtility.HtmlDecode(s);
}
else
{
text = s;
}
}
if (text != null)
{
if (((text is string) && (((string)text).Length == 0)) && ConvertEmptyStringToNull)
{
text = null;
}
if (((text is string) && (((string)text) == nullDisplayText)) && (nullDisplayText.Length > 0))
{
text = null;
}
if (dictionary.Contains(dataField))
{
dictionary[dataField] = text;
}
else
{
dictionary.Add(dataField, text);
}
}
}
}
I have a method in C#, which creates a JSON object of the user credentials.
Below is the CS file.
public string CreateLoginjson(string strErrorType, bool blIsAuthenticated)
{
StringBuilder sbLoginJson = new StringBuilder();
if (blIsAuthenticated)
{
sbLoginJson.Append("{LoginSuccess:1");
}
else
{
sbLoginJson.Append("{LoginSuccess:0");
}
if (strErrorType != string.Empty)
{
if (strErrorType.TrimEnd(new char[] { ',' }) == "Token" ||
strErrorType.TrimEnd(new char[] { ',' }) == "BlankToken")
{
sbLoginJson.Append(",txtTestTokenNumber1:\"Error\"");
sbLoginJson.Append(",txtTestTokenNumber2:\"Error\"");
sbLoginJson.Append(",txtTestTokenNumber3:\"Error\"");
sbLoginJson.Append(",txtTestTokenNumber4:\"Error\"");
}
if (strErrorType.TrimEnd(new char[] { ',' }) == "Password")
{
sbLoginJson.Append(",txtPassword:\"Error\"");
}
if (strErrorType.TrimEnd(new char[] { ',' }) == "UserName")
{
sbLoginJson.Append(",UserName:\"Error\"");
}
string strLoadErrorControlMessage = LoadErrorControl(strErrorType,
string.Empty);
if (strLoadErrorControlMessage!= string.Empty)
{
sbLoginJson.Append(",ErrorMessage:
'" + strLoadErrorControlMessage + "'");
}
}
sbLoginJson.Append("}");
var LoginJson = sbLoginJson.ToString();
return LoginJson;
}
Now, I need to pass the LoginJson to a JS function that checks if incorrect credentials are provided, this function finds the control & adds an attribute to it
JS
function GetLoginJson(strLoginJson) {
if (strLoginJson != '' && strLoginJson != undefined) {
var objLoginJson = strLoginJson;
if (objLoginJson.LoginSuccess == "1") {
}
else if (objLoginJson.LoginSuccess == "0") {
if (objLoginJson.txtUserName != ''
&& objLoginJson.txtUserName != undefined)
{
$('#txtUserName').attr("class", objLoginJson.txtUserName);
}
else
{
$('#txtUserName').attr("class", "Input");
}
if (objLoginJson.txtPassword != ''
&& objLoginJson.txtPassword != undefined)
{
$('#txtPassword').attr("class", objLoginJson.txtPassword);
}
else
{
$('#txtPassword').attr("class", "Input");
}
if (objLoginJson.txtTestTokenNumber1 != ''
&& objLoginJson.txtTestTokenNumber1 != undefined)
{
$('#txtTestTokenNumber1').attr("class",
objLoginJson.txtTestTokenNumber1);
}
else
{
$('#txtTestTokenNumber1').attr("class", "Error");
}
if (objLoginJson.txtTestTokenNumber2 != ''
&& objLoginJson.txtTestTokenNumber2 != undefined)
{
$('#txtTestTokenNumber2').attr("class",
objLoginJson.txtTestTokenNumber2);
}
else
{
$('#txtTestTokenNumber2').attr("class", "Error");
}
if (objLoginJson.txtTestTokenNumber3 != '' &&
objLoginJson.txtTestTokenNumber3 != undefined) {
$('#txtTestTokenNumber3').attr("class",
objLoginJson.txtTestTokenNumber3);
}
else
{
$('#txtTestTokenNumber3').attr("class", "Error");
}
if (objLoginJson.txtTestTokenNumber4 != '' &&
objLoginJson.txtTestTokenNumber4 != undefined) {
$('#txtTestTokenNumber4').attr("class",
objLoginJson.txtTestTokenNumber4);
}
else
{
$('#txtTestTokenNumber4').attr("class", "Error");
}
$('#ErrorControl').html('');
}
}
}
I want to pass the JSON variable from the CS to this jQuery statement `$('#ErrorControl').html('');'
Thanks
If the user provides all the information and clicks something(any control), you can make an ajax request from jquery.
If you are returning some error message from CS, you can use that message directly as
$('#ErrorControl').html(response.d)
d = "string which you retrun from CS".
where response is the parameter for your success function. d is the default property(variable) for the received object.
if you dont want to display string directly, use the returned data and call another javascript function.
Thanks
First of all, you could try the JavaScriptSerializer (chekc the link) to serialize any object into JSON and then send a string response to the client.
For the communication between the server and the client you can use the jquery's ajax call which is calling your webservice (f.e.), or if you building an ASP.NET site or application then you can use PageMethods and calling it directly from javascript.
If you are intrested in the PageMethods option, here is a quite good and easy tutorial.
user1502890,
Server-side
I don't really know C# but it appears that you are trying to build a JSON string directly. It is far more normal (and easier and more reliable) to build an object and then to stringify it into JSON with either a built-in language command or a utility method. I guess this must be possible in C#.
Client-side
Assuming the credentials fields to be in a form with id="credentialsForm" and the server-side script to be requestable as the relative URL "myCredentialsChecker.xtn", then the jQuery will be something like this:
$(function() {
function loginResponse(j) {
j = j || {};
if (j.LoginSuccess) {
//...
}
else {
$('#txtUserName').attr("class", j.txtUserName ? j.txtUserName : "Input");
$('#txtPassword').attr("class", j.txtPassword ? j.txtPassword : "Input");
$('#txtTestTokenNumber1').attr("class", j.txtTestTokenNumber1 ? j.txtTestTokenNumber1 : "Error");
$('#txtTestTokenNumber2').attr("class", j.txtTestTokenNumber2 ? j.txtTestTokenNumber2 : "Error");
$('#txtTestTokenNumber3').attr("class", j.txtTestTokenNumber3 ? j.txtTestTokenNumber3 : "Error");
$('#txtTestTokenNumber4').attr("class", j.txtTestTokenNumber4 ? j.txtTestTokenNumber4 : "Error");
$('#ErrorControl').html('');
}
}
$("#credentialsForm").on('submit', function() {
$.ajax({
url: "myCredentialsChecker.xxx",
data: $(this).serialize(),
type: 'POST', // or 'GET'
dataType: 'json',
success: function(j) {
loginResponse(j);
),
error: function() {
loginResponse();
}
});
return false;
});
});
Notes
Everything in the else{...} clause simplifies as above because '' and undefined are both falsy, so simply testing foo will do the job. The ternary alternaive to if(){...} else{...} also makes for compact code.
I'm not convinced that setting classes to the returned strings is the right thing to do but I've not changed this aspect.
I finally wrote :
CS file as
public string CreateLoginjson(string strErrorType, bool blIsAuthenticated)
{
StringBuilder sbLoginJson = new StringBuilder();
if (blIsAuthenticated)
{
sbLoginJson.Append("{LoginSuccess:1");
}
else
{
sbLoginJson.Append("{LoginSuccess:0");
}
if (strErrorType != string.Empty)
{
if (strErrorType.TrimEnd(new char[] { ',' }) == "Token" || strErrorType.TrimEnd(new char[] { ',' }).Split(new char[] { ',' }).Contains("BlankToken"))
{
sbLoginJson.Append(",txtTestTokenNumber1:\"Error\"");
sbLoginJson.Append(",txtTestTokenNumber2:\"Error\"");
sbLoginJson.Append(",txtTestTokenNumber3:\"Error\"");
sbLoginJson.Append(",txtTestTokenNumber4:\"Error\"");
}
if (strErrorType.TrimEnd(new char[] { ',' }) == "Password" || strErrorType.TrimEnd(new char[] { ',' }).Split(new char[] { ',' }).Contains("BlankPassword"))
{
sbLoginJson.Append(",txtPassword:\"Error\"");
}
if (strErrorType.TrimEnd(new char[] { ',' }) == "UserName" || strErrorType.TrimEnd(new char[] { ',' }).Split(new char[] { ',' }).Contains("BlankUserName"))
{
sbLoginJson.Append(",txtUserName:\"Error\"");
}
string strLoadErrorControlMessage = LoadErrorControl(strErrorType, string.Empty);
if (strLoadErrorControlMessage != string.Empty)
{
PageTestApplicationLogin objPageTestApplicationLogin = new PageTestApplicationLogin(objClientConfiguration);
sbLoginJson.Append(",ErrorMessage:'" + objPageTestApplicationLogin.GetTestApplicationLoginErrorHtml("", strLoadErrorControlMessage).Replace("'", "\"") + "'");
}
sbLoginJson.Append("}");
}
var LoginJson = sbLoginJson.ToString();
return LoginJson;
}
JS file :
if (objLoginJson.ErrorMessage != '' && objLoginJson.ErrorMessage != undefined) {
$('#ErrorControl').html(objLoginJson.ErrorMessage);
$('#ErrorControl').find('#tblLoginError').css('display', 'block');
}
else {
$('#ErrorControl').html("");
$('#ErrorControl').find('#tblLoginError').css('display', 'none');
}
Thank you all for your Suggestions.. Cheers ....