How to disable click action in asp menu in asp.net - asp.net

I have a dynamically generated menu (C#), like this:
MenuItem(string text, string value, string imageUrl, string navigateUrl, string target)
MenuItem AdminLevel1 = new MenuItem("Admin", "Admin"); MenuItem AdminPedidosRegisto = new MenuItem("Questions", "AdminQ");
NavigationMenu.Items.Add(new MenuItem("Messages Received", "AdminMessagesR", "", "./Admin/Messages.ascx", "ContainerIframe")); AdminPedidosRegisto.ChildItems.Add(new MenuItem("Pending", "AdminPending", "", "./Admin/Pedidos.ascx", "ContainerIframe"));
Where 'ContainerIframe' is the iFrame's ID and 'NavigationMenu' is the (asp:Menu)'s ID.
I want to disable the click action in the parent items that don't have an URL set, so the page doesn't refresh when someone clicks it.
Is there a way?

menuitem.NavigateUrl = "javascript:;";

Thanks to #Manibhadra (this is enough for parent items and child items)
window.onload = function ()
{
var menuTable = document.getElementById("<%=NavigationMenu.ClientID%>");
var menuLinks = menuTable.getElementsByTagName("a");
for (i = 0; i < menuLinks.length; i++)
{
menuLinks[i].onclick = function () { }
}
}

if (MenuItem.NavigateUrl == "")
{
MenuItem.Selectable = false;
}

Related

Autofill feature with Listbox in asp.net

i have a Listbox with items being 'first name' loaded from a table of a database,
now i want an autofill feature where if a user types like 'a' all the names starting with 'a' first name should be show in the listbox
and after some button click the original data should be repopulated in the listbox
for 2nd one i.e.. repopulating hope i can do with below code
protected void btnRePopulate_Click(object sender, EventArgs e)
{
DataSet oDs = ReadDataSet();
Listbox1.DataTextField = "Name";
Listbox1.DataValueField = "ID";
Listbox1.DataSource = oDs;
Listbox1.DataBind();
}
but for the 1st i have some things on which iam working (i am using textbox keyup event to fire when the user types 'a' or whatever)
clear the listbox and add the names which starts with 'a', but not sure is it possible from client side
or set another listbox visible with names filtered from the original and hide the original listbox, for which i am not able to set visible property either from js or codebehind
no i dont want to use ajax autofill
is there a better option apart from the above two...
This filtering and resetting is best done on the client side itself. That way you don't make unnecessary server calls. Here is a extension method in jQuery.
$(function() {
$('#select').filterByText($('#textbox'), true);
});
Extension method:
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
if (selectSingleMatch === true &&
$(select).children().length === 1) {
$(select).children().get(0).selected = true;
}
});
});
};
I found this on Lessan Vaezi's blog with a live demo on how to do it.

Returning Arraylist from recursive function for ASP.Net

Please refer the attached screenshot. I have an array of the checkbox and a button for the post back in ASP.Net page. I have written a function as follows to determine what all check boxes have been checked on the button click event: The following code is a part of the business component which is called from ASP.Net. Please let me know how can I return actionArray back to calling functon in ASP.Net page.
public void checkBoxValidation(Control parent, string strKey)
{
XmlDocument getCyleXML = new XmlDocument();
string strChkID="", strActionXPath = "",strAction="";
ArrayList actionArray = new ArrayList();
// Loop through all the controls on the page
foreach (Control c in parent.Controls)
{
// Check and see if it's a checkbox.
if ((c.GetType() == typeof(CheckBox)))
{
// Since its a checkbox, see if this is checked.
if (((CheckBox)(c)).Checked == true)
{
// Find the ID of the checkbox
strChkID = ((CheckBox)(c)).ID.ToString();
getCyleXML = CycleXML(strKey);
strActionXPath = "/Actions/Action[checkbox='" + strChkID + "']/*[self::Name]";
strAction = getCyleXML.SelectSingleNode(strActionXPath).ToString();
actionArray.Add(strAction);
}
}
// Now we need to call itself (recursion) because all items (Panel, GroupBox, etc) is a container so we need to check
// all containers for any checkboxes.
if (c.HasControls())
{
checkBoxValidation(c, strKey);
}
}
}
The code should be like this :
public ArrayList checkBoxValidation(Control parent, string strKey, ArrayList actionArray)
{
XmlDocument getCyleXML = new XmlDocument();
string strChkID="", strActionXPath = "",strAction="";
if(actionArray == null) { actionArray = new ArrayList(); }
// Loop through all the controls on the page
foreach (Control c in parent.Controls)
{
// Check and see if it's a checkbox.
if ((c.GetType() == typeof(CheckBox)))
{
// Since its a checkbox, see if this is checked.
if (((CheckBox)(c)).Checked == true)
{
// Find the ID of the checkbox
strChkID = ((CheckBox)(c)).ID.ToString();
getCyleXML = CycleXML(strKey);
strActionXPath = "/Actions/Action[checkbox='" + strChkID + "']/*self::Name]";
strAction = getCyleXML.SelectSingleNode(strActionXPath).ToString();
actionArray.Add(strAction);
}
}
// Now we need to call itself (recursion) because all items (Panel, GroupBox, etc) is a container so we need to check
// all containers for any checkboxes.
if (c.HasControls())
{
checkBoxValidation(c, strKey, actionArray);
}
}
return actionArray;
}

How can I add dynamic html to a server control?

I am creating a server control that will sit in a aspx page. When the user selects a menu option, html controls (selects, inputs, etc) will have be added dynamically. I can do it using a user control, but I'm not sure how to go about it in a server control.
Can anyone tell me how I can add dynamic html into the control after it's already sitting in a page?
Since you are planning to add several controls as the output of your server control, you should consider inheriting from CompositeControl, this control is designed to work with several constituent controls, minimizing the code needed to do common things like keeping state and handling constituent control events
You need to override the CreateChildControls to add child controls. At the end of this method you should use this.ChildControlsCreated = true; to specify if the child controls were created, this is necessary because the CreateChildControls is called several times during the ASP.Net page life-cycle
You need to apply the same rules that you would typically apply to any server control, for example implement the INamingContainer interface to ensure that child controls will have a unique client ID
This is a simple example:
[DefaultProperty("UserText")]
[ToolboxData(#"<{0}:UserPassword runat=server UserText="""" PasswordText="""" />")]
public class UserPassword : CompositeControl
{
public event EventHandler Submitted = delegate { };
[Bindable(true)]
[Category("Appearance")]
[Description("User text")]
[DefaultValue("")]
[Localizable(true)]
public string UserText
{
get
{
var t = this.FindControl("Username") as TextBox;
return t.Text;
}
set
{
var t = this.FindControl("Username") as TextBox;
t.Text = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[Description("Password text")]
[DefaultValue("")]
[Localizable(true)]
public string PasswordText
{
get
{
var t = this.FindControl("Password") as TextBox;
return t.Text;
}
set
{
var t = this.FindControl("Password") as TextBox;
t.Text = value;
}
}
protected override void CreateChildControls()
{
var p = new Panel { Width= new Unit(200), BackColor = Color.Silver };
var ul = new Label { Text = "Username: " };
var u = new TextBox { ID = "Username" };
var pal = new Label { Text = "Password: " };
var pa = new TextBox { ID = "Password", TextMode = TextBoxMode.Password };
var l = new Literal { Text = "<br />" };
var b = new Button { Text = "Log in" };
b.Click += (x, y) => this.Submitted(x, y);
p.Controls.Add(ul);
p.Controls.Add(u);
p.Controls.Add(l);
p.Controls.Add(pal);
p.Controls.Add(pa);
p.Controls.Add(l);
p.Controls.Add(l);
p.Controls.Add(b);
this.Controls.Add(p);
this.ChildControlsCreated = true;
}
}

accessing checkboxlist text through javascript

I have a checkbox list i have which i have bound some document name to it's text field.now i need to find only the checkboxes which the text contains the .pdf extension and check them all in a single checkbox click.i have written the following javascript but it doesn't work for me
function CheckAllPDF() {
var checkBoxList = document.getElementById("<%= cblFiles.ClientID %>");
var checkBoxes = checkBoxList.getElementsByTagName("input");
for (i = 0; i < checkBoxes.length; i++) {
var string = checkBoxes[i].parentNode.getElementsByTagName('label').innerHTML;
var match = string.indexOf(".pdf");
if (match != -1) {
checkBoxes[i].checked = true;
}
else {
checkBoxes[i].checked = false;
}
}
can some one help?
When you put an asp.net check box list in the page it is translated to a list of input of type checkbox so you need to access each control and check it so you javascript code should look like:
//Get the main id of the asp.net check box list
var checkboxId = '<%= CheckBoxList1.ClientID %>';
//Loop on all generated input check boxes where the count function determine the number of generated checkboxes
for (var i = 0; i < <%= Count() %>; i++) {
//Append the count on the main asp.net check box id the value ('_'+i)
var checkBox = document.getElementById(checkboxId + '_' + i);
var checkBoxValue = checkBox.value;
var match = checkBoxValue.indexOf(".pdf");
if (match != -1) {
checkBox.checked = true;
}
else {
checkBox.checked = false;
}
}
And in your code behind write the count function as follows:
public int Count()
{
return CheckBoxList1.Items.Count;
}

Why my yui datatable within an updatepanel disappears after postback?

I got my YUI datatable rendered with my json datasource inside an updatepanel... If i click a button within that updatepanel causes postback and my yui datatable disappears
Why yui datatable within an updatepanel disappears after postback?
EDIT:
I am rendering YUI Datatable once again after each post back which is not a form submit... I know it is a bad practice...
What can be done for this.... Any suggestion.....
if (!IsPostBack)
{
GetEmployeeView();
}
public void GetEmployeeView()
{
DataTable dt = _employeeController.GetEmployeeView().Tables[0];
HfJsonString.Value = GetJSONString(dt);
Page.ClientScript.RegisterStartupScript(Page.GetType(), "json",
"EmployeeDatatable('" + HfJsonString.Value + "');", true);
}
When i click any button in that page it causes postback and i have to
regenerate YUI Datatable once again with the hiddenfield value containing
json string..
protected void LbCancel_Click(object sender, EventArgs e)
{
HfId.Value = "";
HfDesigId.Value = "";
ScriptManager.RegisterClientScriptBlock(LbCancel, typeof(LinkButton),
"cancel", "EmployeeDatatable('" + HfJsonString.Value + "');, true);
}
My javascript:
function EmployeeDatatable(HfJsonValue){
var myColumnDefs = [
{key:"Identity_No", label:"Id", width:50, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Emp_Name", label:"EmployeeName", width:150, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Address", label:"Address", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Desig_Name", label:"Category", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"", formatter:"checkbox"}
];
var jsonObj=eval('(' + HfJsonValue + ')');
var target = "datatable";
var hfId = "ctl00_ContentPlaceHolder1_HfId";
generateDatatable(target,jsonObj,myColumnDefs,hfId)
}
function generateDatatable(target,jsonObj,myColumnDefs,hfId){
var root;
for(key in jsonObj){
root = key; break;
}
var rootId = "id";
if(jsonObj[root].length>0){
for(key in jsonObj[root][0]){
rootId = key; break;
}
}
YAHOO.example.DynamicData = function() {
var myPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 10,
template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions: [10,25,50,100],
pageLinks: 10 });
// DataSource instance
var myDataSource = new YAHOO.util.DataSource(jsonObj);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {resultsList: root,fields:new Array()};
myDataSource.responseSchema.fields[0]=rootId;
for(var i=0;i<myColumnDefs.length;i++){
myDataSource.responseSchema.fields[i+1] = myColumnDefs[i].key;
}
// DataTable configuration
var myConfigs = {
sortedBy : {key:myDataSource.responseSchema.fields[1], dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
paginator : myPaginator
};
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable(target, myColumnDefs, myDataSource, myConfigs);
myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
myDataTable.subscribe("checkboxClickEvent", function(oArgs){
var hidObj = document.getElementById(hfId);
var elCheckbox = oArgs.target;
var oRecord = this.getRecord(elCheckbox);
var id=oRecord.getData(rootId);
if(elCheckbox.checked){
if(hidObj.value == ""){
hidObj.value = id;
}
else{
hidObj.value += "," + id;
}
}
else{
hidObj.value = removeIdFromArray(""+hfId,id);
}
});
myPaginator.subscribe("changeRequest", function (){
if(document.getElementById(hfId).value != "")
{
if(document.getElementById("ConfirmationPanel").style.display=='block')
{
document.getElementById("ConfirmationPanel").style.display='none';
}
document.getElementById(hfId).value="";
}
return true;
});
myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
return {
ds: myDataSource,
dt: myDataTable
};
}();
}
Hai guys,
I got an answer for my qusetion.... Its my postback that caused the problem and i solved it by making an ajax call using ajax enabled WCF Service in my web application... Everything works fine now....
Anything you are generating client side will have to be regenerated after every page refresh (and after every partial page refresh, if that part contains client-side generated html).
Because the YUI datatable gets its data on the client, you will have to render it again each time you replace that section of html.

Resources