i m working on simple asp.net and in that i am using validators.
my situation is like that i have used reaquired field validator its working fine.
and after that if i ented data and fired insert query then data is inserted and sucessful message is displyed on the lable. but agin if i clik on submit button with empty fields then validator works but the lable of successful message does not disapper. how to hide that lable.
You need to use javascript to hide the success message, here is a sample
<script type="text/javascript">
function hide() {
document.getElementById('<%=lblSuccess.ClientID %>').style.display = 'none';
return false;
}
</script>
<asp:Label ID="lblSuccess" runat="server" Text="Success"></asp:Label>
..your form code
<asp:Button ID="btnOk" runat="server" Text="OK" OnClientClick="hide()" ValidationGroup="ValidateForm" />
Why javascript, the form doesn't get posted because validators don't let the form to be posted if the conditions aren't met, so you are left to hide the message dynamically with javascript
<script type="text/javascript">
function Hide() {
document.getElementById("Lable1").style.display = 'none';
return false;
}
</script>
<asp:Button ID="Button1" OnClientClick="Hide()" runat="server" onclick="Button1_Click" Text="Button"/>
and use
if (Page.IsValid){}
on clik event.
Show us some code of what you're up to and we can tell you more precisely where you are going wrong. In a nutshell though the visibility of that message is going to be persisted through a postback so you have to explicitly tell it to not be visible if validation has failed.
Set the label to visable=false and on save set the text value if required and change visible =true ?
On form load, do something like this:
TheValidMessageLabel.Visible = Page.IsValid;
You are probably just setting the visible state to true when it's valid and never setting it to false again.
Set your success label visibility in page load to false.
And only if operation is successfully set that label visibility to true.
cheers
Related
i want to do validation asking that, are sure you want to delete..?
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>' OnCommand="Calling_Delete">Delete</asp:LinkButton>
The easiest way to do it is to use Confirm Button extender. Just drag this control next to the linkbutton and set the Confirmbutton externders TargetControlID to the Id of the Linkbutton. Everything else will be taken care of by the control.
More info- http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
Use OnClientClick property to attach the java-script that will do the prompting. For example,
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>'
OnClientClick="return confirm('Are sure you want to delete..?');"
OnCommand="Calling_Delete">Delete</asp:LinkButton>
This answer has one way to do it, using jQuery and a jQuery UI dialog
One advantage of using a javascript dialog such as that provided by jQuery UI is that the popup dialog is modal only for the web page on which it is displayed. You can still access other tabs within your browser while the popup is displayed.
Other solutions that use the javascript confirm function will force the user to dismiss the confirmation dialog before switching to another browser tab.
if u'd like to use custom confirmation ( like jquery dialog,bootboxjs etc.. ) then you have to generate button's "postback string" or get it somehow. asp.net gives such as postback name after rendering the page; __doPostBack('ctl00$ContentPlaceHolder1$btnDeleteSelected',''). after realizing this i wrote a js function which is generates button's postback str;
function PostBackBtnMake(id) { // id : ContentPlaceHolder1_btnDeleteSelected
var result;
var temp = id.split('_');
result = 'ctl00$' + temp[0] + '$' + temp[1];
return result;
}
then i be able to use in custom confirmation box (in this case i used bootboxjs);
function PostBackBtn(e) {
var _result = false;
bootbox.confirm("Are you sure?", function (result) {
if (result) {
__doPostBack(PostBackBtnMake(e.id), '')
}
});
return _result;
}
it's worked for me, i hope it helps you too.
I'm trying to get a sequence of things to happen in the correct order, but no luck. What I have is a number of fields with asp:ReuiredFieldValidators and asp:ValidatorCallout to display validation messages. This is triggered with a button Save with validation="true".
If all validates, it should display a modal dialog asking for two choises on how to save the data. No matter the answer, it should always continue at this stage to code behind save function.The AjaxToolkit_ModalPopupExtender is connected to the same save button.
What happens is that the validation callouts and modal dialog is shown at the same time.
Searched for tips and help but haven't found any, for me, helpful! Most grateful for any help!
Cheers
/Johan
You can show the ModalPopup from codebehind(in BtnSave.Click-handler) if the page is valid:
Page.Validate("YourValidationGroup");
If(Page.IsValid){
ModalPopup1.Show();
}
Therefor you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
You must move to Code Behind only when the Page is validated in client side. You can do it using OnClientClick of button
<asp:Button ID="ShowDialog" onClientClick = "return ValidatePage();"
runat="server" />
<script type="text/javascript">
function ValidatePage() {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
}
if (Page_IsValid) {
// do something
alert('Page is valid!');
return true;
}
else {
// do something else
alert('Page is not valid!');
return false;
}
}
</script>
I have some code where I need two separate required field validators for one control, both in separate validation groups which are then validated by two separate buttons.
This approach works well when the buttons are clicked but both validators show if I enter a value in the textbox and then remove it.
Is there a way to turn this"lost focus" validation off? I only need it to validate when the buttons are clicked.
EDIT
Unfortunately, if I set EnableClientScript=false then I dont have any client notifications. What I want is for the dynamic error message to show (effectivly in the OnClientClick event of the button) but not the "lost focus" of the textbox.
Is there some way I can disable or "unhook" the lostfocus client event?
EDIT
A combination dDejan's answer and womp's answeer here sorted the problem perfectly.
My final code looks like this (for anyone else with a similar situation)...
Javascript...
<script type="text/javascript">
$(document).ready(function() {
$('body').fadeIn(500);
//Turn off all validation = its switched on dynamically
$.each(Page_Validators, function(index, validator) {
ValidatorEnable(validator, false);
});
});
function ToggleValidators(GroupName) {
$.each(Page_Validators, function(index, validator) {
if (validator.validationGroup == GroupName) {
ValidatorEnable(validator, true);
} else {
ValidatorEnable(validator, false);
}
});
}
</script>
ASPX Control Example...
<telerik:RadTextBox Width="196px" ID="txtFirstName" runat="server" MaxLength="50" Skin="Black"></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="valFirstName" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForEmail"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForSubmit"></asp:RequiredFieldValidator>
ASPX Button Code...
<asp:Button ID="btnGetConfCode" runat="server" Text="Get Confirmation Code" OnClientClick="ToggleValidators('NeededForEmail')" OnClick="btnGetConfCode_Click" Width="100%" ValidationGroup="NeededForEmail"/>
<asp:Button ID="btnRegisterUser" runat="server" Text="Register" OnClientClick="ToggleValidators('NeededForSubmit')" OnClick="btnRegisterUser_Click" Width="100px" ValidationGroup="NeededForSubmit" />
So, now there is no validation until a user clicks either the "Get Email Confirmation Code" button or the "Register" button.
If they click the "Get Email Confirmation Code" button all of the controls validate apart from the textbox where the user is to input the email validation code and we only see one validator message.
If they click the "Register" Button then all of the controls validate and we only see one validation message.
If either button is pressed, the user goes back, adds and then removes some text then we only see one validator. Before this change you used to see both messages saying the same thing.
Thank you for help guys
You can set if the validators are "active" or not with client side code using the ValidatorEnable function. Basically it goes like this
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state); //where state is boolean
You can also trigger the validator to validate on some event (like for example the click of the buttons) using the ValidatorValidate(validator) function.
I am not sure which would work better for you (enabling/disabling the validators or custom triggering of the validation) but I suggest this article that will guide you in the right direction
ASP.NET Validation in Depth
There's no way to unhook them if EnableClientScript=true.
What you could do is set it to false. Then create a javascript validation method that is called on your submit-button onClientClick event.
In your method, you would have to call ValidatorValidate(control) for each control you want to validate client side
There's an example here:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
You could turn off the javascript validation by setting EnableClientScript="false" that would get rid of the lost focus validation.
You can use Custom Validator controls instead and either validate the input using Javascript on the client or within the event handler on the server. Ensure you set ValidateEmptyText="true" on the validation controls otherwise the events will not fire on an empty field.
Try to Enable on Both button click using javascript and disable it on textbox blur event.
Try resetting the onchange event for the input-control.
$(document).ready(function () {
$("#controlid").each(function () { this.onchange = null; })
});
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state);
It is working in javascript but when we use the page.Isvalid function on Server side it creates the problem to check page is valid or not.
simply type this code in page_load event
textboxname.Attributes.Add("onblur","ValidatorOnChange(event);");
I've got a checkbox that's set up as below:
<asp:CheckBox ID="myCheckbox" runat="Server" OnClick="showLoadingScreen(this.checked);" AutoPostBack="true" Text="Check me for more data!" />
The function showLoadingScreen is as below:
function showLoadingScreen(isChecked) {
if (isChecked)
{
document.getElementById('form1').style.display='none';
document.getElementById('img_loading').style.display='block';
}
else { return false; }
}
I've added the else clause in hopes that I can get it to only post back when the checkbox is checked, but it's posting back in either case.
I've got a grid on the page (inside form1) that has a set of data loaded into it on page load, but in order to add some extra data to it I've added this checkbox (its a longer running process, so I only want to load it on demand, not upfront). When it's checked I want to show the loading gif, postback, grab the data, and return. If the box gets unchecked I don't want to do anything, since leaving more than enough data on the page is perfectly fine (that is to say, the data displayed upfront is a subset of the data displayed when the checkbox is checked).
Is there any way to make it so the checkbox auto posts back on checked, but not on unchecked?
Edit: Using Dark Falcon's suggestion, I've modified the checkbox to look like:
<asp:CheckBox ID="myCheckbox" runat="Server" OnClick="return showLoadingScreen(this.checked);" AutoPostBack="true" Text="Include HQ Values" />
And the javascript to be:
function showLoadingScreen(checked) {
alert(checked);
if (checked)
{
document.getElementById('form1').style.display='none';
document.getElementById('img_loading').style.display='block';
document.form1.submit(); //my own addition, to get it to post back
}
else { return false; }
}
Now, it posts back on checked, but the box is not able to be unchecked anymore. As you can see I've added an alert to show the value being passed in. It's passing in the correct value when you uncheck the box (false), but then it somehow gets checked again.
It's not a huge issue, since there's really no reason to ever uncheck the box (since as I stated before, the dataset when checked is a superset of the unchecked dataset), but I'd still like to know why it's doing that. Any ideas?
Do not set AutoPostBack in this case. "AutoPostBack" means post back to the server any time the value of this control changes... which is NOT what you want.
Instead, use GetPostBackEventReference(myCheckbox,"") to get the appropriate postback script and call this from your showLoadingScreen method if the checkbox is checked.
For your onclick handler, you need to do:
return showLoadingScreen(this.checked);
Try to avoid using _doPostback as it is a hack which you will have to know what control ID is posting back and other parameters for that Javascript function from Microsoft ASP.NET. To understand what's happening behind the scene, you have to know why there is a postback and how to prevent the postback from happening.
Here's what's happening with an ASP.NET checkbox (ASP:Checkbox) when auto-postback is set:
<ASP:Checkbox runat="server" id="chkCheckbox" AutoPostback="true" onclick="return isDoPostback(this.checked);" ClientIdMode="static" ... />
generated HTML code is:
<input type="checkbox" ... id="..." onclick="return isDoPostback(this.checked);_doPostback(...);" .../>
The custom onclick event is appended to the beginning of the onclick event of the checkbox. No matter what you do, that prepended function call will execute. Worst off, if you have a return value, the _doPostback will never get executed.
This is what you really want to do (I use a mix of jQuery and native Javascript here):
var checkbox = $("#chkCheckbox");
...
checkbox .on("change", function(e)
{ if(this.checked)
{
var isConfirmedToContinue = confirm("Continue with Postback?");
if(!isConfirmedToContinue)
{ this.checked = false; //Uncheck the checkbox since the user canceled out
var onClickDelegate = this.onclick;
if(onClickDelegate)
{ var me = this;
this.removeEventListener("click", onClickDelegate); //Remove the onclick event so that auto-postback no longer happens
setTimeout(function()
{ //Add back the onclick delegate after 250ms
me.addEventListener("click", onClickDelegate);
}, 250);
this.onclick = null; //Remove the current onclick event by nulling it out
}
}
}
});
Try using a JS routine for checking whether it is checked, and if it is set to true, try doing:
_doPostBack(checkElementReference.name, "");
_doPostBack is responsible for performing posts to the server for controls that don't normally postback. You have to pass the name of the element, which on the server happens to be the UniqueID property for the server-side checkbox control.
I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.
What can I do to resolve this?
If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:
<asp:Label runat="server" id="Label1" style="display: none;" />
Then, you could make it visible on the client side with:
document.getElementById('Label1').style.display = 'inherit';
You could make it hidden again with:
document.getElementById('Label1').style.display = 'none';
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.
Try this.
<asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" />
<script type="text/javascript">
function ShowButton() {
var buttonID = '<%= myButton.ClientID %>';
var button = document.getElementById(buttonID);
if(button) { button.style.display = 'inherit'; }
}
</script>
Don't use server-side code to do this because that would require a postback. Instead of using Visibility="false", you can just set a CSS property that hides the button. Then, in javascript, switch that property back whenever you want to show the button again.
The ClientID is used because it can be different from the server ID if the button is inside a Naming Container control. These include Panels of various sorts.
Continuing with what Dave Ward said:
You can't set the Visible property to false because the control will not be rendered.
You should use the Style property to set it's display to none.
Page/Control design
<asp:Label runat="server" ID="Label1" Style="display: none;" />
<asp:Button runat="server" ID="Button1" />
Code behind
Somewhere in the load section:
Label label1 = (Label)FindControl("Label1");
((Label)FindControl("Button1")).OnClientClick = "ToggleVisibility('" + label1.ClientID + "')";
Javascript file
function ToggleVisibility(elementID)
{
var element = document.getElementByID(elementID);
if (element.style.display = 'none')
{
element.style.display = 'inherit';
}
else
{
element.style.display = 'none';
}
}
Of course, if you don't want to toggle but just to show the button/label then adjust the javascript method accordingly.
The important point here is that you need to send the information about the ClientID of the control that you want to manipulate on the client side to the javascript file either setting global variables or through a function parameter as in my example.
You need to be wary of XSS when doing stuff like this:
document.getElementById('<%= Label1.ClientID %>').style.display
The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the AntiXss library's methods:
document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display
This is the easiest way I found:
BtnUpload.Style.Add("display", "none");
FileUploader.Style.Add("display", "none");
BtnAccept.Style.Add("display", "inherit");
BtnClear.Style.Add("display", "inherit");
I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.
If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.
Make sure the Visible property is set to true or the control won't render to the page. Then you can use script to manipulate it.