Popup a CalendarBehavior from Javascript - asp.net

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, ...

Related

ASP dynamic usercontrols in a gridview do not update

I have a got Gridview, that gets its data by:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
}
After a button click the database is updated and the new data is shown. Everything works fine.
Now I have to replace the string with an Usercontrol:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
for (int i = 0; i < gridViewer..Rows.Count; i++)
{
UCControl dum = (UCControl)LoadControl("~/UCControl.ascx");
dum.SetData(gridViewer.Rows[i].Cells[0].Text, false);
gridViewer.Rows[i].Cells[0].Controls.Clear();
gridViewer.Rows[i].Cells[0].Controls.Add(dum);
}
}
After first Page_Load(), everything is shown correctly. But when I click my buttons, the Usercontrols do not repaint. The data is set correctly inside, but it does not update.
Because this Control reacts by javascript on UserInputs on the client side, every Usercontrol has got his own Id that is set by
this.ID = "UCControl" + data[0];
data[0] is unique, but known during the whole process.
Can somebody tell me why the UserControl does not repaint? Or better: How do I tell the Usercontrols to update?
From your code I would say that once the data is bound then you can't go in immediately after and start to change it. You would need to hook into one of the databinding events.
If you were using a list viem ItemDataBound would be a good candidate to hook into. But the GridView has a more limited set of events and doesn't offer that level of control - so you are a bit stuck on that score.
In my experience using dynamic controls in asp.net (LoadControl) is just a bit fraught. I think a better option would be to publicly expose a property in your user control and bind to that.
This question gives a good description of how to achieve this
asp.net user controls binds inside gridview
Hope that helps

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

Web Application Architecture (ASP.NET 3.5,JavaScript)

hey all ,
background -
I'm using an activx that allow me to access some information on the client side,
By using the activex events and callback i'm updating server side from client.
i wrote a user control that register all activex's events so when one of the events occuer there is a callback to the server that handle this event.
I need to write some other user controls based on this control so on every callback this user controls will be render on the client side.
My question is -
what is the best way to make a shared infrastructure that handle this events and render the right content base on user controls?
is there any other ways i can use ?
thanks!
hey! thanks for your fast reply,
first of all , i'm calling the activex using object tags,
HtmlGenericControl SkypeObject = new HtmlGenericControl("object");
SkypeObject.Attributes.Add("id", "Skype");
SkypeObject.Attributes.Add("codeBase", "http://ip/Skype4COM.dll");
SkypeObject.Attributes.Add("classid", "clsid:830690FC-BF2F-47A6-AC2D-330BCB402664");
SkypeObject.Attributes.Add("name", "Skype");
write callback :
string SkypeAsyncCallbackOnEvent = ClientScript.GetCallbackEventReference(this, "values", ClientScriptName, "context", true);
string SkypeCallbackFunction = "\n<script>\n";
SkypeCallbackFunction += "function SkypeCallback(values,context) {\n";
SkypeCallbackFunction += SkypeAsyncCallbackOnEvent + "\n}\n";
SkypeCallbackFunction += "</script>";
then i register the active'x events :
string SkypeOnUserStatusChange = "\n<script for=\"Skype\" event=\"UserStatus(Status)\">\n";
SkypeOnUserStatusChange += "var values = {\"StatusInfo\" : Status};\n";
SkypeOnUserStatusChange += "var myArray = {\"key\" : \"Status\", \"values\" : values};\n";
SkypeOnUserStatusChange += "var s=JSON.stringify(myArray);";
SkypeOnUserStatusChange += "SkypeCallback(s,null);\n";
SkypeOnUserStatusChange += "</script>";
this is my base user control (in short) so on each events callback is occur.
(this can be change to any class it doesnt metter right now)
now i want to create custom controls that will show the data back from the client.
in my opinion, i can change the call back reference client script to the one that exist in the Child Control and register the child control to the events of the base control.
what do you think ?
thanks :)
A little more info on your project would be helpful, but I think you would be well served using two approaches, one to handle the logic/events... and one to actually handle the visual updates - with some glue in the middle to make it all work like a charm.
First, the events. I could envision some sort of javascript class that registers with your activex control and binds methods to the various event handlers. This class would also expose methods you could bind functions to that would provide callbacks to your display logic.
Second, I would recommend using a library like jQuery to help with the heavy lifting of modifying the user page.
function eventTrap() {}
eventTrap.prototype.hookActiveX() { // your code to attach to your activex object }
eventTrap.prototype.register(event, callback) { // code to register for an event and callback }
// actually use it...
var trapObj = new eventTrap();
trapObj.hookActiveX();
trapObj.register("click", function(){alert('click');});

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.

ASP.Net Custom Client-Side Validation

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.

Resources