Can I call a function after a ValidationSummary? - c#

I have a ValidationSummary on client side (which should be called by asp:LinkButton) that check my RequiredFieldValidator and CustomValidator :
<asp:ValidationSummary
ID="valSum"
runat="server"
CssClass="label"
HeaderText="There are these errors:"
ShowSummary="False"
ShowMessageBox="True"
EnableClientScript="True"
DisplayMode="BulletList">
</asp:ValidationSummary>
and I need, if there are the errors (so there are empty fields or the custom validators fail) call another javascript function.
I really hope that this is possible on .NET 3.5, right?
I've read a similar question on SO here, but is not clear at all.

Place this script at the page's end:
<script type="text/javascript">
var originalValidationSummaryOnSubmit = ValidationSummaryOnSubmit;
ValidationSummaryOnSubmit = function (validationGroup) {
originalValidationSummaryOnSubmit(validationGroup);
if (Page_IsValid === false) {
alert("boo!");
}
}
</script>

Yes this is possible. You will need to change the OnClientClick property of your linkbutton and/or other controls causing the validation to perform. Also put your CausesValidation property to false.
<asp:LinkButton ID="lnkButton1" runat="server" CausesValidation="false" OnClientClick="return DoValidation('');" ... />
Javascript function:
function DoValidation(validationGroup) {
var isValid = Page_ClientValidate(validationGroup);
if (!isValid){
isValid = DoSomethingElse();
}
return isValid;
}
If you want to only validate a group you can pass the name of the group to the 'DoValidation' function.
<asp:LinkButton ID="lnkButton1" runat="server" CausesValidation="false" OnClientClick="return DoValidation('NameOfGroup');" ... />

Related

How to show pop up div from server side on button click

I am working on Payment page and i want to show a popup for showing message your payment is processing. so for now i am using CustomValidator and Submit Button. and i want to show this popup when Args is valid. my code is.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" OnServerValidate="CustomValidator1_ServerValidate"
EnableClientScript="true" ValidationGroup="Authorize"></asp:CustomValidator>
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true" CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click" OnClientClick="validate(ContentPlaceHolder1_chk_agree);" />
One better approach is to go with "updateProgress".
Place your submit button inside a updatePanel and place a loading gif image inside updateProgress which will show below loading image when payment progress is going on and will close automatically when payment is complete.
Loading ....
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/loadingNew.gif" AlternateText="Loading ..." ToolTip="Loading ..."/>
</ProgressTemplate>
</asp:UpdateProgress>
To show a message box after validation, you can do the following:
Add the following javascript to your <head>
<script language="javascript">
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
alert('Your payment is processing');
}
return isValid;
}
</script>
Then, change your button like this:
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true"
CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click"
OnClientClick="return SubmitButton_ClientClick();" />
An even better approach is to use a popup div - here is a very basic example:
Add this somewhere in your <body>
<div id="popup_box" style="height:300;width:300;position:absolute;top:150;left:350;border:3px solid red;background:#d8d8d8;display:none;">
<h1>Payment is processing</h1>
<button id="popupBoxClose" onclick="document.getElementById("popup_box").style.display = 'none';">Close</button>
</div>
And modify the SubmitButton_ClientClick like this:
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
document.getElementById("popup_box").style.display = '';
}
return isValid;
}

How to pass control.ClientId to an OnClick function in ASP.NET?

I'm trying to turn on/off various RequiredFieldValidator controls when checkboxes are checked/unchecked, based on this question. But rather than having a separate js function for each checkbox I want to pass in the ClientID of the input to validate, something like this (only one INPUT here but you can see once it's working I can add more INPUTs without more js):
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClick="updateValidator('<%= rfvSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
Currently that scriptlet txtSubject.ClientID isn't evaluated, just output directly. I'm sure this is simple but I just don't know the appropriate syntax.
How about adding it via the codebehind (or a script section):
checkSubjectRequired.Attributes.Add("onclick", "updateValidator(" +
txtSubject.ClientID + ")");
This explaination of ClientID may be helpful.
This is because; ASP.NET parser can not parse server tag "<% = %>" for a server side control (i.e. control made as runat='server').
Use the following:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClick="updateValidator('<%#txtSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
You could just do this:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClientClick="updateValidator(this.id);" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>

how can i pass parameters from javascript to hidden field in controls vb.net

i have a control that has two asp:HiddenField
<asp:HiddenField runat="server" ID="tabTitle" />
<asp:HiddenField runat="server" ID="tabMenu" />
this control load in a page called Alarms
the control on the alarms page look like this
<alarm:SubscriptionPanel ID="pnlSubscription" runat="server" />
what iam trying to do is passing value from pagealarms to the control hidden fields and there is a function at the control code behind that reads the hidden fields values
Question is how can i pass javascript values to hidden field in controls on page load
thanks in advance
You can use JQuery for it like this
Example :
$("input[type=hidden][id='<%=tabTitle.ClientID%>']").val("Hello World");
$("input[type=hidden][id='<%=tabMenu.ClientID%>']").val("Hello World");
If you are using ASP.NET 4.0 your best bet is to set the ClientIDMode property on those controls to static and then simply use javascript to populate the hidden elements using plain ol' document.getElementById(). Something like this:
<asp:HiddenField runat="server" ID="tabTitle" ClientIDMode="Static" />
//since the id mode in the hidden element is static;
//you should be able to do this safely:
document.getElementById('tabTitle').value = myvalue;
If you are not on ASP.NET 4.0; jQuery will help here since you can find an element using partial matching as HatSoft showed you in his answer but with a slight difference:
$("input[type=hidden][id*='tabTitle']").val("Hello World");
Note the id*= part. This gets all input elements whose ids contain the word tabTitle
Besides the approach commented by #Icarus, you could expose a JavaScript function from your control.
The problem you would face if you use ClientIDMode=Static in that, you would be restricted to add only one alarm:SubscriptionPanel control to your page
If you are planning to use only one control on each page, then the easiest approach is the one commented by #Icarus, however I would consider it as a temporal approach
This alternative encapsulates the logic where it really belongs, inside the custom control:
Output
ASCX
<div id="<%: this.ClientID %>">
<asp:HiddenField runat="server" ID="hidden1" Value="one" />
<asp:HiddenField runat="server" ID="hidden2" />
<asp:Button Text="Post me" runat="server" OnClick="postme_Click" />
<asp:Label runat="server" ID="lbl"></asp:Label>
<script type="text/javascript">
$(function () {
var myObj = {
setHidden1: function (myValue) {
$("#<%: this.hidden1.ClientID %>").val(myValue);
},
getHidden1: function () {
return $("#<%: this.hidden1.ClientID %>").val();
},
helloWorld: function () {
alert("hellow world");
}
};
$("#<%: this.ClientID %>").data("data", myObj);
});
</script>
</div>
ASCX code behind
protected void postme_Click(object sender, EventArgs e)
{
this.lbl.Text = "Posted: " + this.hidden1.Value;
}
ASPX
<script type="text/javascript">
$(function () {
$("#myPageButton").click(function () {
$("#<%: this.myControl.ClientID %>").data("data").setHidden1("plop");
$("#<%: this.myControl2.ClientID %>").data("data").setHidden1("plop2");
});
});
</script>
<input type="button" id="myPageButton" value="Set Hidden value" />
<uc1:EncapsulateJavaScriptLogicInUserControl ID="myControl"
runat="server" />
<uc1:EncapsulateJavaScriptLogicInUserControl ID="myControl2"
runat="server" />
<uc1:EncapsulateJavaScriptLogicInUserControl ID="myControl3"
runat="server" />
I just found another way, that looks even more object oriented, however, it requires you to use the Microsoft AJAX library.
ASCX
Change: $("#<%: this.ClientID %>").data("data", myObj);
Into: $.extend($get("<%: this.ClientID %>"), myObj);
ASPX
Change:
$("#<%: this.myControl.ClientID %>").data("data").setHidden1("plop");
$("#<%: this.myControl2.ClientID %>").data("data").setHidden1("plop2");
Into:
$get("<%: this.myControl.ClientID %>").setHidden1("plop");
$get("<%: this.myControl2.ClientID %>").setHidden1("plop2");
With this approach you remove the use of the .data jQuery function

asp.net: run javascript on click?

i have a form and a button a form:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" />
i have a method in my c# program. the method is called SubmitData
however i would also like to run a javascript function on this button click as well. how do i do this?
here is my javascript function:
var selectedLanguages = new Array();
jQuery('#lstProblems option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
i got it from here: jquery listbox return what user selected
how do i run it ? do i have to put it in <script></script> and do some_Function(etc...) ?
you should use the OnClientClick='myJsFunc();'
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="SubmitData" OnClientClick="aaa()" />
<script type="text/javascript">
function aaa()
{
var selectedLanguages = new Array();
jQuery('#lstProblems option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
}
</script>
You can use OnClientClick event
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Your javascript function" OnClick="SubmitData" />
Set up your server side event code the way it seems to be already, then in the Page_Load method of your code behind add the following line:
Button1.Attributes.Add("onclick","yourJavascriptFunction();");
EDIT: To run the function from your edited question, simply create a function of the same name in your javascript file. Something like this:
<script type="text/javascript">
function yourJavascriptFunction()
{
var selectedLanguages = new Array();
jQuery('#lstProblems option:selected').each(function() {
selectedLanguages.push(jQuery(this).val());
});
}
</script>

AJAX ToolKit TabContainer: Can I capture the "Active Tab Panel Changing" event

I have an AJAX ToolKit TabContainer control with several TabPanels. I want to validate the contents of the current active TabPanel to prevent user from working on other ones in case data was invalid.
If you need to do a TabPanelChangingEvent SERVER side, You will need to do this by Altering the ajaxcontroltoolkit Source code.
Good news : you could easily get it
Here a new solution that does almost what your need :
The OnClientActiveTabChanged event is raised
The tabcontainer New Tab index is saved in a Hiddenfield
The tabindex is reset to it's old value (so it wont change right now)
The form trigger a asyncpostback using a hidden button.
Within the hidden button's Click event, the OldTabIndex and NewTabIndex are retrieved.
At the end of the Click event, the tabcontainer's tabindex is switched to the new value.
So, the hidden button's Click event is executed before the TabContainer tab is changed.
aspx:
<asp:Button runat="server" ID="hiddenTargetControlForTabContainer" style="display:none" />
<asp:UpdatePanel ID="TabContainerUpdatePanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="hiddenTargetControlForTabContainer" />
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="TabContainerActiveTab" runat="server" Value="0" />
<AjaxControlToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"
OnClientActiveTabChanged="OrderTabContainerClientActiveTabChanged" >
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel1"
HeaderText="TabPanel1"
>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel2"
HeaderText="TabPanel2" >
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
</AjaxControlToolkit:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
var TabContainerActiveTabControlID = '<%= TabContainerActiveTab.ClientID %>';
var hiddenTargetControlForTabContainerControlID = '<%= hiddenTargetControlForTabContainer.uniqueID %>';
function OrderTabContainerClientActiveTabChanged(sender, args) {
var TabContainerActiveTabControl = $get(TabContainerActiveTabControlID);
var OldtabIndex = parseInt(TabContainerActiveTabControl.value);
var NewtabIndex = sender.get_activeTabIndex();
if (!(OldtabIndex == NewtabIndex)) {
sender.set_activeTabIndex(OldtabIndex);
TabContainerActiveTabControl.value = NewtabIndex;
__doPostBack(hiddenTargetControlForTabContainerControlID, '');
}
}
Code behind:
Protected Sub hiddenTargetControlForTabContainer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles hiddenTargetControlForTabContainer.Click
Dim oldActiveTabIndex = TabContainer1.ActiveTabIndex
Dim newActiveTabIndex As Integer = Convert.ToInt32(TabContainerActiveTab.Value)
'your stuff here
TabContainer1.ActiveTabIndex = newActiveTabIndex
End Sub
Problem: Ajax TabContainer the ActiveTabChanged event shows incorrect ActiveTabIndex.
For eg. TabContainer contain 3 tabs, if second tab is hide(visible = false on server side) then on click of third tab, we get ActiveTabChanged = 1 not 2 (expected active index is 2 on server side code).
Solution:
Register the clientside event of the tab container:
OnClientActiveTabChanged="Tab_SelectionChanged"
Then define the javascript function to handle the above event which will internally store the tab index in a hidden variable.
function Tab_SelectionChanged(sender,e)
{
document.getElementById('<%=hdntabIndex.ClientID %>').value = sender.get_activeTabIndex();
}
Use the hidden variable(hdntabIndex) in the code behind where ever you need the active tab index.
You should do it using JavaScript.
Here an example I made, the trick is to use ValidationGroup and save the Old tab Index at the end of the function called by the OnClientActiveTabChanged
<AjaxControlToolkit:TabContainer ID="TabContainer1" runat="server" Height="138px"
Width="402px" ActiveTabIndex="0"
OnClientActiveTabChanged="ValidateTab" >
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel1"
HeaderText="TabPanel1"
>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="TextBox1"
ValidationGroup="TabPanel1"
/>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel2"
HeaderText="TabPanel2" >
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="TextBox2"
ValidationGroup="TabPanel2"
/>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
</AjaxControlToolkit:TabContainer>
<script type="text/javascript">
var OldtabIndex = 0;
function ValidateTab(sender, args) {
if (OldtabIndex == 0) {
if (!Page_ClientValidate('TabPanel1')) {
sender.set_activeTabIndex(OldtabIndex);
}
}
else if (OldtabIndex == 1) {
if (!Page_ClientValidate('TabPanel2')) {
sender.set_activeTabIndex(OldtabIndex);
}
}
OldtabIndex = sender.get_activeTabIndex();
}
</Script>
I know I'm probably late to answering this question, but hopefully, I can offer some assistance to someone who's pot-committed like I was to the TabPanels.
Add the OnClientActiveTabChanged="showMap" to the ajaxToolkit:TabContainer. My function is obviously called showMap (had to hide and show the Google Street Map, because TabContainer screws it all up. So I had to move the Google Street Map outside of the container and then 'fake' put it back in the container).
<ajaxToolkit:TabContainer runat="server" ID="tabs" OnClientActiveTabChanged="showMap">
<ajaxToolkit:TabPanel runat="server" ID="pnlZones" HeaderText="Delivery Zones">
<ContentTemplate>
...
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
Then create the javascript:
<script type="text/javascript">
function showMap() {
var tabID = $('.ajax__tab_active').attr('id');
if (tabID.indexOf('pnlZone') > 0) {
$('#mapHider').css('height', '600px');
}
else {
$('#mapHider').css('height', '0');
}
}
</script>
We can then find the active tab by the class .ajax__tab active, which is what TabContainer will set the active class to. Snag the ID (.attr('id')) with jQuery... And voila, we now which tab we're currently on.
For this I change the height of the class from 0 to 600px. With the overflow set to hidden, it makes it seem like the map is on the page and only in that container, but it isn't.
Hopefully, this helps!! Good luck.

Categories

Resources