ASP.Net Custom Client-Side Validation - asp.net

I have a custom validation function in JavaScript in a user control on a .Net 2.0 web site which checks to see that the fee paid is not in excess of the fee amount due.
I've placed the validator code in the ascx file, and I have also tried using Page.ClientScript.RegisterClientScriptBlock() and in both cases the validation fires, but cannot find the JavaScript function.
The output in Firefox's error console is "feeAmountCheck is not defined". Here is the function (this was taken directly from firefox->view source)
<script type="text/javascript">
function feeAmountCheck(source, arguments)
{
var amountDue = document.getElementById('ctl00_footerContentHolder_Fees1_FeeDue');
var amountPaid = document.getElementById('ctl00_footerContentHolder_Fees1_FeePaid');
if (amountDue.value > 0 && amountDue >= amountPaid)
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
return arguments;
}
</script>
Any ideas as to why the function isn't being found? How can I remedy this without having to add the function to my master page or consuming page?

Try changing the argument names to sender and args. And, after you have it working, switch the call over to ScriptManager.RegisterClientScriptBlock, regardless of AJAX use.

When you're using .Net 2.0 and Ajax - you should use:
ScriptManager.RegisterClientScriptBlock
It will work better in Ajax environments then the old Page.ClientScript version

Also you could use:
var amountDue = document.getElementById('<%=YourControlName.ClientID%>');
That will automatically resolve the client id for the element without you having to figure out that it's called 'ctl00_footerContentHolder_Fees1_FeeDue'.

While I would still like an answer to why my javascript wasn't being recognized, the solution I found in the meantime (and should have done in the first place) is to use an Asp:CompareValidator instead of an Asp:CustomValidator.

Related

ASP.Net Auto-populate field based on other fields

I've just moved to web development and need to know how i can implement below requirement using asp.net and vb.net.
I have three fields in a form which are filled by users. Based on these three values, i need to auto-populate the 4th field. I have planned to implement this in the following way
Write a separate class file with a function to calculate the possible values for the 4th fields based on 1st 3 inputs. This function can return some where between 1-10 values. So I've decided to use drop-down for 4th field, and allow users to select the appropriate value.
Call the above function in onchange function of 3rd field and take and use the return values to populate the 4th field. I'm planning to get the return values in array field.(Does this need a post back?)
Please let me know how if there is better way to implement this.
Thanks.
You may want to consider doing this with Javascript. You could read and control the fields pretty easily with pure Javascript, or using a nice library like jQuery (my favorite). If you did it this way, no post-back would be required and the 4th field would update immediately. (Nice for your users)
You can also do it with ASP.NET for the most part. "onchange" in ASP.NET still requires Javascript as far as I know, it just does some of it for you. A post-back will definitely happen when you change something.
You need javascript or to set autopostback=true on your form elements.
From a user perspective the best thing is to use javascript to populate the field for display, BUT when the form is submitted use your backend function to validate it. This will make sure the user didn't change the value.
An easy way is to use jQuery for the UI (that way you don't have to worry about long winded javascript and deal with browser compatibility as it's already taken care of for you) and have it call to the server for the data. For the server, your easiest route is to return JSON for looping values.
Include your jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
Then add in a handle for the JavaScript:
<script type="text/javascript">
function autoPopulate() {
var value1 = $('#ddl1').val();
var value2 = $('#ddl2').val();
var value3 = $('#ddl3').val();
var url = 'path/to/your/file.aspx?value1=' + value1 + '&value2=' + value2 + '&value3=' + value3;
$.getJSON(url, function(data) {
data == null ? return false : data = eval(data);
var ddl = $('#ddl4')[0];
for (i = 0; i < data.length; i++) {
var option = new Option(data[i][0], data[i][1]);
if ($.browser.msie) {
ddl.add(option);
} else {
ddl.add(option, null);
}
}
}
}
</script>
(Yes, I know I used a native loop but I'm little lazy here today :) )
Now, for your server side code you'll want your code your page to return data in the format of:
[['value1','text1'],['value2','text2'],['value3','value3']]
so something like:
<script type="vb" runat="server">
Private Sub Page_Init()
// get your data
// loop through it and add in values
// ex.
Dim result As String = "[" //start multi-dimensional array
For Each Item As String In data
result += String.Format("['{0}','{1}'],", _value, _text)
Next
result = result.SubString(0, result.Length - 1) // removes trailing comma
result += "]" // closes off m-array
Response.Write(result)
Response.Flush()
End Sub
</script>

Asp.net: How to call a javascript function at the end of button click code behind

My motto is to call a Java script function at the end of button click code behind. ie, firstly i need to execute the server side function after which my java script function should get invoked.
My server side method is as follows
protected string SaveEmbedURL_click()
{
if (txtembedurl.Text != null)
{
School aschool = new School();
aschool.SchoolId = CurrentSchool.SchoolId;
aschool.EmbedUrl = txtembedurl.Text;
SchoolRespository.updateEmbedUrl(aschool);
return "true";
}
}
My Java script function is as follows
function SaveEmbedUrlClientSide() {
admin_CustomizeTheme.SaveEmbedURL_click(true);
$('#lbl_embedcode').removeClass('hide').addClass('show');
$('#embedCode').removeClass('hide').addClass('show');
CopyToClipboard("embedCode");
}
How can i achieve this?
Thanks.
I'm pretty sure all you need is to add this
RegisterStartupScript("YourJavaScript", "SaveEmbedUrlClientSide()");
"YourJavaScript" is an arbitrary string that is used to identify the Javascript.
Here's the relevant MSDN article.
Page.RegisterStartupScript is now obsolete, so I would use this code.
ClientScript.RegisterStartupScript(Page.GetType, "Javascript", "SaveEmbedUrlClientSide();", true);
RegisterStartupScript requires Type, Reference, Code, render script blocks. Reference Here

Popup a CalendarBehavior from Javascript

How can I embbed all the scripts needed by the CalendarBehavior in a page, without actually using the server-side control (CalendarExtender). The reason I can't use a server side extender is that I have a page with, possibly, hundreds of Date controls; I want to be able lazy-load the calendars as needed (when the user clicks in the control).
The code that creates the calendar from javascript is the following:
cal = $create(AjaxControlToolkit.CalendarBehavior,
{ 'id': owner.id + '_calendar', 'cssClass': 'calExt', 'format': format },
null, null, owner);
The problem is that without including all the needed js from the AjaxControlToolkit resources, it will throw the error:
AjaxControlToolkit is undefined.
Thank you very much,
Florin S.
I've found the following hack that will register all the scripts and css references exposed by the CalendarExtender. I think the solution is generic so that it can be used with other extenders:
ScriptManager manager = ScriptManager.GetCurrent(Page);
if (manager != null)
{
foreach (ScriptReference reference in ScriptObjectBuilder.GetScriptReferences(typeof(CalendarExtender)))
{
manager.Scripts.Add(reference);
}
CalendarExtender extender = new CalendarExtender();
Page.Form.Controls.Add(extender);
ScriptObjectBuilder.RegisterCssReferences(extender);
Page.Form.Controls.Remove(extender);
}
The temporary extender instance is needed for the RegisterCssReferences call, otherwise it will throw an error.
It works, but YMMV.
I had the same issue.
I found that, in javascript-land, instead of AjaxControlToolkit you should use Sys.Extended.UI.
So, instead of:
cal = $create(AjaxControlToolkit.CalendarBehavior, ...
you do this:
cal = $create(Sys.Extended.UI.CalendarBehavior, ...

Duplicate JavaScript without a debugger statement?

I have and ASP.NET 3.5 page where I need to debug some JavaScript code.
function checkAll(isChecked)
{
debugger;
var dataGridElements = document.getElementById('" + DataGridSearchResults.ClientID + #"').getElementsByTagName('input');
for (var i = 0; i < dataGridElements.length; i++)
{
var e = dataGridElements[i];
if ((e.type=='checkbox') && (!e.disabled))
{
e.checked = isChecked;
}
}
}
As you can see, I added a debugger statement in the first line. For some reason, when i execute the page, the javascript (which is in a string variable and registered with Page.ClientScript.RegisterClientScript statement) is in my source code twice! The second block doesn't have my debugger statement either! I checked the project, this block of Javascript is only listed once in the project.
Any ideas? (the client i am running on is IE8 if that makes a difference)
Figured it out. The base page that this control was on (the javascript was in an ASCX file) was a page that had a tab strip on it. One of the other tabs had the code copy and pasted with the exact same signature, just a grid name difference. Once i changed the signature on my set of code, it worked fine.

Passing flash variables to asp.net

I don't know much about Flash but we are working on a site that has a flash form and when the users pick an option, like selecting a value from a drop down list, we need the value to be passed to asp.net server-side code. What's the easiest way to do this?
Flash can invoke server side service. So use GET or POST to pass data
You could explore these options:
1) Communicate between the SWF and the containing page through JavaScript
2) Communicate via asp.net webservices from the SWF directly to the webservice.
3) Not sure but could probably do a POST to a processing aspx page?
HTH
I think a good option is to use the XML class so consider this:
var xmlRequest = new XML();
xmlRequest.onLoad = parseXMLResponse;
xmlRequest.load("http://yourpathtoyourserver/file.aspx?listselectedvalue=something");
function parseXMLRequest(loaded)
{
trace("hi");
}
You can also have the page give you data back this way so it's not just one way communication.
Assuming you are using Action Script 2.
Read the important notes at the bottom of each codes pertain to sending and retrieving data from flash to .net page. Explanation of the code is in the comment inside the code.
Flash Part (Action Script 2)
//function to send collected form data to asp.net page
//use other control/button to call this function
//important: in order for the 'onLoad' event to work correctly, this function has to be 'Void'
function sendForm():Void
{
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you for filling up the form!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "The form you are trying to fill up has an error!";
}
}
//this is the collected data from the form
lv_out.userName = txtUserName.text;
lv_out.userAddress = txtUserAddress.text;
lv_out.userBirthday = txtUserBirthday.text;
//begin invoke .net page
lv_out.sendAndLoad("ProcessDataForm.aspx", lv_in, "POST");
}
Important note:
The function that contain onLoad event, in this case sendForm function, has to be Void function, meaning it's not returning value. If this function return value, what happen is the function will be executed all the way without waiting for the returned data from .net page, thus the onLoad event will not be set properly.
.Net Part
public void ProcessData
{
//process the data here
Response.Write("status=processed&");
}
Important note:
To send data/message back to flash, you can use Response.Write. However, if you want Action Script to parse the posted message/data from .Net page keep in mind you have to include & symbol at the end of the message. When parsing data/message, Action Script will stop at & symbol, thus leave the rest of the message alone and only get the message under sent variable.

Resources