namespacing javascript in user control - asp.net

I have created a jquery slider usercontrol in asp.net using jquery UI slider. The user control have some javascript functions to set the value of the slider when the textbox value changes in the main page. Everything works fine if I have only usercontrol. But if I have multiple user controls, I am not sure how to namespace the javascript so that it calls the function inside the specific user control.
Thanks,
Sridhar.

I would suggest object orienting your code - something like this (Obviously this is only pseudocode...)
function Slider(parentElement, id){
var element = ... // get / create your element here
// attach appropriate event listeners here...
element.onclick = function(){
//event handling code...
}
this.setValue = function(value){
// set value of element
}
this.getValue = function(){
//get value of element
}
}
var sliderA = new Slider(document.getElementById('anElement'));
var sliderB = new Slider(document.getElementById('anotherElement'));

Related

ASP.NET #Html.TextBoxFor : How to not lose value user entered in case page is refreshed?

I am using MVC hmtl helper syntax for textbox i.e.#Html.TextBoxFor(m => m.Id). I have quite lengthy form with multiple textboxes, radio buttons and drop downs.
Problem is that when I am refreshing the page, the values filled in the controls i.e. textbox,dropdown,radio-buttons filled get lost.
How can I avoid this and restore the filled values of the form even if user refreshes the page? Any other method than localstorage/cookies etc.?
you can create your jquery custom method with sessionStorage and you can add it to jquery.fn object to keep your form data even after page refresh
(function($){
// To Load your form values from sessionStorage, and set sessionStorage when value is changed.
$.fn.keepValue = function(name) {
if(!name) {
name= "";
}
return this.each(function() {
var $this = $(this);
var id = $this.attr('id');
var storage_name = namespace + id;
var value;
// Store form changes in a cookie
$this.change(function() {
sessionStorage.setItem(storage_name, $this.val());
});
value = sessionStorage.getItem(id);
// Don't overwrite value if it's already exist
if(!$this.val()) {
$this.val(name + value);
}
});
};
})(jQuery);
$(document).ready(function(){
$('#YourElementId').keepValue();
});

How to attach a callback to a custom confirmation dialog in Google App Maker?

I am creating a custom confirmation dialog in Google App Maker and would like the Confirm button to call a passed-in function. I don't see an "onclick" event in the button widget. Any suggestions on how to do this?
function confirmationDialog(msg, confirmFunction)
{
var desc = app.pageFragments.ConfirmationDialog.descendants;
var label = desc.Label;
var confirmButton = desc.Confirm;
label.text = msg;
confirmButton.onClick = confirmFunction; // does not work
app.showDialog(app.pageFragments.ConfirmationDialog);
}
Thanks
It'd be great if this was a bit easier, but the best bet is to use Custom Properties (https://developers.google.com/appmaker/ui/viewfragments).
You can set up a custom property of type "Dynamic" and call it anything, take "onConfirmCallback", for example. Then you can set the function on that custom property:
Code to invoke dialog:
app.pageFragments.ConfirmationDialog.properties.onConfirmCallback = function(param) {
alert(param);
};
app.showDialog(app.pageFragments.ConfirmationDialog);
And then in the onClick for the close button:
app.pageFragments.ConfirmationDialog.properties.onConfirmCallback("hi");
app.closeDialog();
Also note that there are slightly better ways to set up labels than in your example, also using custom properties.
Create custom properties for any widget properties you want to customize, and then bind those custom properties (#properties.propertyName) to the widget property. For example you might have a confirmText property, with the confirm buttons text property boudn to #properties.confirmText.
Then when you invoke your dialog, you can just set those custom properties. Quick modification of your example code using properties for everything:
function confirmationDialog(msg, confirmFunction)
{
var properties = app.pageFragments.ConfirmationDialog.properties;
properties.text = msg;
properties.confirmCallback = confirmFunction;
app.showDialog(app.pageFragments.ConfirmationDialog);
}
For my confirmation dialogs, I just set the onclick of the OK button before I show the dialog (everything is in one place, which is easier for the dummy (me) who will have to maintain it in six months:
var dialog=app.pages.ConfirmationDialog;
dialog.descendants.message.text='Are you sure...?'
dialog.descendants.btnOk.getElement().onclick=function(){
//do something here
app.closeDialog();
});
};
app.showDialog(dialog);
}

How to know which button of User Control is clicked from parent form Asp.net?

I want to capture which button is clicked in page load method of code behind file.
Button is user control button and It does not post back. Since it used by many other forms, I don't want to changes that button.
I tried this
Dim ButtonID As String = Request("btnRefresh.ID")
But it doesn't work.
Is it possible to know without touching in user control and using Javascript?
Thank you
As described here How to check whether ASP.NET button is clicked or not on page load:
The method: Request.Params.Get("__EVENTTARGET"); will work for
CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work
for Button controls such as Buttons and ImageButtons
But you have a workaround, first of all you have to define a hidden field in the Parent Page. In this field you will store which button inside the user control was clicked using javascript/jquery. And then in your Parent Page Page_Load method you just read the hiddenField.Value property:
JQuery
1) Add listener to every input type submit button:
$(document).ready(function () {
$("input[type=\"submit\"]").on("click", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
2) [Better one] Add listener to some indentificable div inside the user control and delegate the event to child inputs like this:
$(document).ready(function () {
$("#someElementOfUserControl").on("click", "input[type=\"submit\"]", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
Javascript
Since everything done with JQuery can be done with Javascript you can do the following (i will not write both samples, just one):
function handleClick(event) {
alert(event.target.name);
document.getElementById("hiddenField1").value = event.target.name;
}
var inputsInUC = document.getElementsByTagName('input');
for (i = 0; i < inputsInUC.length; i++) {
inputsInUC[i].addEventListener('click', handleClick, false);
}
Remember to define this javascript after all your html elements.
EDIT:
Also, for the completeness of the answer let me tell you that the proper way in case you can change the user control behaviour is to use events as described here How do i raise an event in a usercontrol and catch it in mainpage?

ASP.NET - How can I add a new javascript from a user control loaded by callback?

I'm doing a menu that loads levels dynamicly, when you click on a item the next level is loaded asynchronously. For each menu item I have a user control. Every user control is declared in its parent, for example, the "secondlevelcontrol" has the reference to "thirdlevelcontrol".
With this level of nesting, I want to manage the asynchronous calls on every user control so, when the first level is loaded the javascript to load the second is loaded too. When the second level is loaded the javascript to load the third is loaded too.
To do asynchronous calls I'm implementing ICallbackEventHandler interface. As you can see in the examples, controls are added to the page as plain html. The method "ProcessOnLoadEvent" executes all lines of the "OnLoad" event of the user control.
An example of the implementation is this for the user control of fourth level:
public string GetCallbackResult()
{
return _callbackRendering;
}
public void RaiseCallbackEvent(string itemId)
{
var id = Int32.Parse(itemId);
var menu = new LateralMenu();
var currentChildren = menu.GetNodesById(id, 1);
var ctrl = this.Page.LoadControl(USER_CONTROL_FIVE_LEVEL_RELATIVE_PATH) as LeftSideFifthLevel;
ctrl.Items = currentChildren.Children;
ctrl.ProcessOnLoadEvent();
_callbackRendering = ctrl.GetHtml();
}
And this is the code for the fifth level user control:
public void ProcessOnLoadEvent()
{
EnsureChildControls();
if (null != RepeaterMenu)
{
SettingCallbackReference();
Visible = null != Items && 0 < Items.Count;
if (null != Items && 0 < Items.Count)
{
RepeaterMenu.DataSource = Items;
RepeaterMenu.DataBind();
}
}
}
public void RaiseCallbackEvent(string itemId)
{
var id = Int32.Parse(itemId);
var menu = new LateralMenu();
var currentChildren = menu.GetNodesById(id, 1);
var ctrl = this.Page.LoadControl(USER_CONTROL_SIX_LEVEL_RELATIVE_PATH) as LeftSideSixthLevel;
ctrl.Items = currentChildren.Children;
ctrl.ProcessOnLoadEvent();
_callbackRendering = ctrl.GetHtml();
}
public void SettingCallbackReference()
{
var cm = this.Page.ClientScript;
var cbRef = cm.GetCallbackEventReference(this, "itemId", "AnchorLevel5_OnClick_Callback", "ctx");
var cbScript = "function AnchorLevel5_OnClick(itemId, ctx){ new Menu().empty(ctx); " + cbRef + "; }";
cbScript += "function AnchorLevel5_OnClick_Callback(htmlText, ctx){ new Menu().render(htmlText, ctx); }";
cm.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);
}
My problem is that levels beyond second level never work because the javascript associated with the user control ("SettingCallbackReference" method) has no html to put on the page.
Is there any way to create some user controls created dynamicly that implements ICallbackEventHandler interface that add new user controls to the page? Or, Am I doing something wrong and this is not the right way to implement this behaviour?
Thanks!!!
I suspect that you are probably going about this the wrong way. Take a look at the answer to this question: How to lazy load Infragistics UltraWebTree control?
This question was specifically about lazy-loading a tree view, but the same principles apply for lazy loading menu items. Follow these steps:
On first page load, render the top level menu
Include a function on the page that makes an ajax call to the server with the
parent id and retuns the next level items for that parent (getNodes in my example)
Bind this function to the click event of the top level menu items (that have sub items)
In the success handler of the ajax call, inject the returned menu items below
the parent and bind the same function to the click event of these items only.
On callback, be careful not to bind the function to the click event of ALL menu items, because then you will end up getting the function bound multiple times to the top level items and called multiple times. Just bind to the returned items.
Also, you need some way of determining that an item's sub items have already been loaded. That is what the following line in my example was for, but you might need something slightly different:
if (jQuery(nodesDiv).text() == 'Loading...') {
I used jQuery because it is the most concise, but you culd do this in pure js - I wouldn't recommend it.

Getting JS Error (for - event.srcElement.id) in WebForm

I am building a dynamic user control (ascx) which contains a placeholder. Inside the placeholder, there will be n tables. Inside each table, in one of the cells i have the link button as below.
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.NavigateUrl = "javascript:JS_Click();";
I have to call a JS function on the link button click (no postback).
In the JS function, i have to get the id of the control that invoked that JS function. In this case, it will be link button. I am writing the below code in the JS Function:
var ctrl = event.srcElement.id;
but i am getting 'Object Required' error in javaScript.
Few other things: This user control will be loaded in default.aspx page and the JS Function i am writing in default.aspx.
I am not sure why this is not working. I am using IE6/7, VS 2005. Is there any other function or way available to get the srcElement.id. Please help.
Try passing this along when you invoke the method
lnkButton.NavigateUrl = "javascript:JS_Click(this);";
then you can write this in your JS_Click event
function JS_Click(obj)
{
alert("Now I have my object " + obj.id);
}
Another option would be to use jQuery and wire up to the click event on your link buttons.
Add a CssClass attribute to the LinkButton's you are creating:
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.CssClass = "linkButton";
Then write the follwoing JS/ JQuery in your ASPX page:
$(document).ready(function()
{
$('.linkButton', '#userControlID').click(function(e)
{
alert('You clicked linkbutton with ID ' + e.target.id);
});
});
In the above example each link button has class="linkButton" and they are contained within your usercontrol with ID="userControlID".

Resources