How to validate dynamically created control? - asp.net

I have an asp.net page, some of its controls are created dynamically, these controls are one of the following; textbox, calendar, or dropdownlist.
These controls in some cases, should be validated based on flag read from db?
Is there any way to validate
dynamically created controls?

Basically you will need to create your validators via code and attach them to the dynamically created controls via code too. The page will then render with your validators in the page for you.
If validation requires a flag to be read from the db then perhaps use a custom validator which will allow you to set up your specific logic on both the client and server for your specific validation requirements. You don't have to provide client validation if you don't want to.

You can create validators at the same time you create those controls

When you are creating any control dynamically, also attach with them desired Validator control and you can enable/disable validator controls at run time.

I got a solution for that problem.
One of the main problems that I had with this page that it's ajax-enabled and I need to validate dynamically created controls.
My solution and it works properly, while creating the Control, I added an input attribute to it markes it as it is required or not, and another attribute that marks it as it is a field to be validated or not?
Using Javascript, I go through all input tags with attribute "dynamic control" and based on "to validate attribut", I validate it or not. Simple, right?
Sample Code:
While control creating, mark it like the following
txtBox.Attributes.Add("Type", "T"); // Type of control.
txtBox.Attributes.Add("IsKeyField", "Y"); // Is dynamically created field.
txtBox.Attributes.Add("IsMandatory", "Y"); // Is mandatory or not?
JavaScript code
var inputControls = document.getElementsByTagName("input");
for(var i=0 ; i<inputControls.length ; i++)
{
if ( inputControls[i].getAttribute("IsKeyField") == "Y" )
{
if (inputControls[i].getAttribute("Type") == "T" || (inputControls[i].getAttribute("Type") == "C"))
{
if(inputControls[i].getAttribute("IsMandatory") == "Y")
{
if(inputControls[i].value == "")
{
errorMsg += "\n" + inputControls[i].getAttribute("KeyField_Name") + " is required.";
isValidated = false;
}
}
}
}
}
Of course, you can call that code while clicking the required button.
btnUpload.Attributes.Add("onClick", "javascript:if(!ValidateMandatoryFields()) return false;");

Related

Hiding buttons in one web form through another web from in asp.net

I have a problem and it is like that I have two forms in asp.net, In one form I have Button1 one and in another form I have two buttons, Button1 and Buton2 now when I click Button1 in first web form the buttons of other web form should hide, how this can be done in asp.net
Solution1 : You can use Sessions as below on Button_Click Event
Session["DisableButtons"] = "True"
In 2nd page of Load Event you can check as below
if(!IsPostBack)
{
if (Session["DisableButtons"] = "True")
{
btn1.Visible = False;
btn2.Visible = False;
}
}
Solution 2 : You can send a variable's value in the URL when you are doing Response.Redirect and you can fetch from URL using Request.QueryString.
Try using jQuery
$(document).ready(function(){
$("#ButtonID1").click(function(){
$("#ButtonID2").hide() //or .toggle(); if you want to hide/show
});
})
Send values from one form to another form
you can use the logic from here for hiding the contents of webfroms using another either you can use Session .
I don't have enough Reputation else it will be posted in comment
.
Thank you
Udit Bhardwaj

fill DropdownList from xml using ajax

I have on one page a dropdownlist which I would like to use AJAX in order to populate it from a XML file. Is there a way to tell AJAX to run only certain asp.net method without using WebServices? Any other solution is welcome but the only restriction is that it would be made on the server side (and not with js for example)?
thanks!
This is possible through a variety of means - one approach is to use jQuery on the client-side to generate the AJAX request like so (binding to the page ready here, but it could be bound to the SELECT change event):
$(document).ready( function () {
$.get('/target-url.aspx?someparam=somevalue', function(data) {
// process the returned data - dependant on the format - assuming JSON here.
var items = data['items'];
// may wish to clear the contents of the SELECT box.
// spin through and add OPTION elements
for(var i = 0; i < items.length; i++) {
$('#selectid').append('<option>'+items[i]+'</option>');
}
}
}
Where selectid is the ID of the dropdownlist element (use the ClientId if in ASP.NET).
Then you need to write some code in ASP.NET to respond to the AJAX request with your desired logic.
Some useful links:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/append/
See here for an example of using jQuery and ASP.NET with JSON:
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

How can I get value from radio-button inserted into innerHtml

I have sort of a table with a radio-button column. I managed to make radio-button column work dynamically inserting into a cell (div if matter). But, on postback innerHtml hasn't been updated with "checked" attribute.
Could you give me an idea how can I find out (on the server) if radio-button has been checked?
More info: This is on user control inside update panel.
This would be good post on my topic, still doesn't help
Any reason you cannot use a standard asp:RadioButton and use javascript to ensure it is mutually exclusive. I have done this before by adding a custom attribute to the radiobutton and then using a js function to uncheck all items with that attribute and then check the selected one. This works around the IE issue which prevents the groupname attribute from working on radioboxes that are in different containers.
radioButton.InputAttributes.Add("ClientGroupName", "grpRadioList");
radioButton.InputAttributes.Add("onclick",
string.Format(
"javascript:radiobuttonToggle('{0}','ClientGroupName','grpRadioList');"
,radioButton.ClientID));
and use the following JS to uncheck all radios and then check the one you want.
Note i used InputAttributes instead of Attributes as the radiobutton is wrapped inside a span tag so InputAttributes is for items added to the actual input control rather than the span.
function radiobuttonToggle(selectedRB, attribName, attribValue)
{
var objRadio = document.getElementById(selectedRB);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i];
if (elm.type == 'radio')
{
if(elm.getAttribute(attribName) == attribValue)
elm.checked = false;
}
}
objRadio.checked = true;
}
You can then expose radioButton.Checked as a property in your CS file and reuse this as a control.
Check Form.Request("radio-name") != null
You only get a non-null value when it's been checked.
Make sure your page elements are being rebuilt correctly on postback. Any binding process that inserted the radio buttons the first time around will have to be re-run before you can access them the second time.
Here is a working example, first I add radios to my webform by the method you linked :
function addRadio()
{
try{
rdo = document.createElement('<input type="radio" name="fldID" />');
}catch(err){
rdo = document.createElement('input');
}
rdo.setAttribute('type','radio');
rdo.setAttribute('name','fldID');
document.getElementById('container').appendChild(rdo);
}
Then at code behind I used only the code below to get the radio's value :
string value = Request["fldID"];
So, be sure you're trying to get the name of the radio buttons at server side. You should use name attribute at server side, not id.

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

Programmatically triggering events in Javascript for IE using jQuery

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know)
This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event.
When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.
Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.
To explain what I'm doing specifically:
I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.
The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method.
Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should.
I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.
Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?
I've found this problem reported several other places, but they offer no solutions:
jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator
ASP.NET forums, bug with ValidatorOnChange() function
I had the same problem. Solved by using this function:
jQuery.fn.extend({
fire: function(evttype){
el = this.get(0);
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(evttype, false, false);
el.dispatchEvent(evt);
} else if (document.createEventObject) {
el.fireEvent('on' + evttype);
}
return this;
}
});
So my "onSelect" event handler to datepicker looks like:
if ($.browser.msie) {
datepickerOptions = $.extend(datepickerOptions, {
onSelect: function(){
$(this).fire("change").blur();
}
});
}
I solved the issue with a patch:
window.ValidatorHookupEvent = function(control, eventType, body) {
$(control).bind(eventType.slice(2), new Function("event", body));
};
Update: I've submitted the issue to MS (link).
From what you're describing, this problem is likely a result of the unique event bubbling model that IE uses for JS.
My only real answer is to ditch the ASP.NET validators and use a jQuery form validation plugin instead. Then your textbox can just be a regular ASP Webforms control and when the contents change and a postback occures all is good. In addition you keep more client-side concerns seperated from the server code.
I've never had much luck mixing Webform Client controls (like the Form Validation controls) with external JS libraries like jQuery. I've found the better route is just to go with one or the other, but not to mix and match.
Not the answer you're probably looking for.
If you want to go with a jQuery form validation plugin concider this one jQuery Form Validation
Consider setting the hidden field _EVENTTARGET value before initiating the event with javascript. You'll need to set it to the server side id (replace underscore with $ in the client id) for the server to understand it. I do this on button clicks that I simulate so that the server side can determine which OnClick method to fire when the result gets posted back -- Ajax or not, doesn't really matter.
This is an endemic problem with jQuery datepickers and ASP validation controls.
As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.
I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).
The bit that fails is
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
which throws an error when it tries to get a length for the undefined 'vals'.
I just added
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.
Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.
// Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
function ValidatorOnChange(event) {
if (!event) {
event = window.event;
}
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof (targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
var i;
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
This is how I solved a simlar issue.
Wrote an onSelect() handler for the datepicker.
link text
In that function, called __doPostBack('textboxcontrolid','').
This triggered a partial postback for the textbox to the server, which called the validators in turn.

Resources