Javascript tabs: call event onclick - c#

I got some code I need to change. it is build by others, and not very neat...
There is a javascript tabcontrol, containing 4 tabs, which contains gridviews.
All the 4 gridviews are build during the load of the page, but I want them to load, when you activate the tabs (as it is possible to watch the side, while you don't need the specific gridviews to see)
So, my question is: how to call an event (that loads the gridview) from an javascript tab?
how the tabs are generated: (generated code, I know, horrible)
var obj = 0;
var oid = 0;
var otb = 0;
var myTabs = new Array();
var myTabitems = new Array();
var myTabitem = new Array();
var myTabContent = new Array();
var myLists = new Array();
function showTabContent(tab)
{
tb = tab.obj;
id = tab.nr;
if (myTabs[tb].oid != -1)
{
myTabs[tb].myTabContent[myTabs[tb].oid].style.display = 'none';
myTabs[tb].myTabitem[myTabs[tb].oid].className -= " active";
}
myTabs[tb].myTabContent[id].style.display = 'block';
myTabs[tb].myTabitem[id].className += " active";
myTabs[tb].oid = id;
}
function boTabs()
{
var myBlocks = new Array();
myBlocks = document.getElementsByTagName("div");
var stopit = myBlocks.length;
for (var g = 0; g < stopit; g++)
{
if (myBlocks[g].className == "tabs")
{
myTabs.push(myBlocks[g]);
}
}
var stopit2 = myTabs.length;
for (var i = 0; i < stopit2; i++)
{
myTabs[i].myLists = myTabs[i].getElementsByTagName("ul");
if (myTabs[i].myLists[0].className == "tabs")
{
myTabs[i].myTabitems = myTabs[i].myLists[0].getElementsByTagName("li");
}
var stopit3 = myTabs[i].myTabitems.length;
myTabs[i].obj = i;
myTabs[i].myTabitem = new Array();
myTabs[i].myTabContent = new Array();
for (var j = 0; j < stopit3; j++)
{
myTabs[i].myTabitem.push(myTabs[i].myTabitems[j]);
myTabs[i].myTabitem[j].nr = j; myTabs[i].myTabitem[j].obj = i;
myTabs[i].myTabitem[j].onclick = function() { showTabContent(this); };
}
var myTabDivs = myTabs[i].getElementsByTagName("div");
for (var j = 0; j < myTabDivs.length; j++)
{
if (myTabDivs[j].className == "tabcontent")
{
myTabs[i].myTabContent.push(myTabDivs[j]);
}
}
myTabs[i].myTabitem[0].className += " active";
myTabs[i].myTabContent[0].style.display = 'block';
myTabs[i].oid = 0;
myTabDivs = null;
}
myBlocks = null;
}
onload = boTabs;

I would change it entirely to use JQuery Tabs and JQuery AJAX to load the grids

If you want a JS solution, you have to build the gridview table yourself using JS code... If you want the server to do the work, you need an UpdatePanel, and make use of the client _doPostBack method. If you like this approach, the Ajax Control Toolkit tab container can be configured to postback to the server whenever the tab changes, which you can wrap this control with an update panel, and it looks like everything is being done with JS code. Alternatively, you can also use a web service that binds a gridview and returns the HTML too... not tried that yet, but seen it done.
HTH, if you let me know what option you prefer, I could update accordingly.

I now got the tabcontrol made by JQuery and CSS.
at this moment all 4 gridviews are bound at Page_Load, but, as it takes time to run te sproc's behind the gridview, it takes a few seconds. Therefore I want to load them on tabclick... The UpdatePanel seems the best way...
JQuery:
$(document).ready(function()
{
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function()
{
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});

Related

C#: How to using global variable with Javascript

everyone!
I'm learning ASP.NET MVC and have some question.
My problem is Passing Data from View to Controller.
This my Code:
#{
string listID = "";
}
and I try to use this variable:
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
#listID = listId;
return listId;
}
Finalize, I want to pass #listID to Controller:
#using (Html.BeginForm("DeleteChecked", "Category", new { listID }, FormMethod.Post)){ }
It is simple problem about multi delete with checkbox.
Help me, please.
You cannot pass a javascript variable to your controller.
But you can post it as part form data with the help of hidden field.
Better add a hidden field and set it in a Javascript and post
#using (Html.BeginForm("DeleteChecked", "Category", FormMethod.Post)){
Html.HiddenFieldFor(m=>m.MyList, new {#id="my-list-data"})
..other controls and your submit button
}
In a Javascript
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
$('#my-list-data').val(listId);
}
You cannot do that.
The aspx\ascx\cshtml etc. page is built in the server side while the js is computed on the client's side.
You can add C# string to js functions but they will be hard coded when they get to the client.
All the C# expression are evaluated before they get to the client and before the js is computed.
Here's an example:
This is what you see on the aspx\ascx\cshtml file.
<%
string str = 'test';
%>
function jsFunc(){
var myVar = '<%=str%>';
}
This is what the client gets:
function jsFunc(){
var myVar = 'test';
}

How to get value of selected checkboxlist items using javascript in asp.net

I am working on an asp.net project in which i have a checkboxlist which i have bound using
DataTable dt = new Process_Hotels().SelectAllFacilty();
if (dt.Rows.Count > 0)
{
cblHotelFacility.DataSource = dt;
cblHotelFacility.DataTextField = "Facility";
cblHotelFacility.DataValueField = "ID";
cblHotelFacility.DataBind();
foreach (ListItem li in cblHotelFacility.Items)
{
li.Attributes.Add("JSvalue", li.Value);
}
}
and now i want to get selected value ID of checkboxlist using javascript on button click.For that i have following javascript code on button click:
<script type="text/javascript">
function test() {
var checkList1 = document.getElementById('<%= cblHotelFacility.ClientID %>');
var checkBoxList1 = checkList1.getElementsByTagName("input");
var checkBoxSelectedItems1 = new Array();
for (var i = 0; i < checkBoxList1.length; i++) {
if (checkBoxList1[i].checked) {
checkBoxSelectedItems1.push(checkBoxList1[i].value);
//alert('checked:' + checkBoxSelectedItems1.push(checkBoxList1[i].getAttribute("JSvalue")).value);
alert('checked - : ' + checkBoxList1[i].value)
}
}
}
</script>
but the on clicking button the selected checkboxlist is showing 0. I want to get ID of selected checkboxlist items.Please help.
Try this :
<script type = "text/javascript">
function GetCheckBoxListValues(chkBoxID)
{
var chkBox = document.getElementById('<%= cblHotelFacility.ClientID %>');
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++)
{
if(options[i].checked)
{
alert(listOfSpans[i].attributes["JSvalue"].value);
}
}
}
</script>
Try debugging
for (var i = 0; i < checkBoxList1.length; i++) {
console.log(checkBoxList1[i])
if (checkBoxList1[i].checked) {
checkBoxSelectedItems1.push(checkBoxList1[i].value);
//alert('checked:' + checkBoxSelectedItems1.push(checkBoxList1[i].getAttribute("JSvalue")).value);
alert('checked - : ' + checkBoxList1[i].value)
}
}
Check to see id console.log() gives you any information about the object by pressing F12 on console window. Install firebug plugin for Firefox.
May this code help you:
function CheckBoxCheckOrNot(jobskill) {
var c = document.getElementById(jobskill).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
if (c[i].checked) {
alert('checkbox checked');
}
else {
alert('checkbox unchecked');
}
}
}
}
note: jobskill is a container id which contain all check boxes.

How to get values from dynamically generated controls in asp.net c#?

I know this is a well asked question and I found some marked as answers but those doesn't solve my problem. Please have a look at my codes..
Method to Display dynamic controls
private void ShowControlsByFormId()
{
List<FormControlsBO> list = new List<FormControlsBO>();
list = new FormControlsDA().FormControls_GetByFormId(Convert.ToInt32(ddlForm.SelectedValue.ToString()));
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
DynamicControl dynamicControl = CommonUtility.GenerateControl(list[i]);
pnlInput.Controls.Add(new LiteralControl("<tr><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControlLiteral);
pnlInput.Controls.Add(new LiteralControl("</td><td></td><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControl);
pnlInput.Controls.Add(new LiteralControl("</td><tr><br/><br/>"));
}
pnlAction.Visible = true;
}
else
{
pnlAction.Visible = false;
}
}
Method to Generate dynamic controls
public static DynamicControl GenerateControl(FormControlsBO bo)
{
DynamicControl dynamicControl = new DynamicControl();
Control control = new Control();
LiteralControl literal = new LiteralControl();
switch (bo.FieldType)
{
case "TextBox":
control = new TextBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "RadioButton":
control = new RadioButton();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "CheckBox":
control = new CheckBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "DropDownList":
control = new DropDownList();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
}
control.ClientIDMode = ClientIDMode.Static;
dynamicControl.GeneratedControl = control;
dynamicControl.GeneratedControlLiteral = literal;
return dynamicControl;
}
Method to Save data
private void FormRecords_Save()
{
List<FormControlsBO> list = new List<FormControlsBO>();
FormControlsBO bo = new FormControlsBO();
foreach (Control ctl in pnlInput.Controls)
{
CommonUtility.DataFiller(bo, ctl);
list.Add(bo);
}
Boolean result = false;
result = new FormControlsDA().FormRecords_Save(list);
if(result == true)
{
lblMessage.Text = "Form data saved successfully";
}
else
{
lblMessage.Text = "Form data not saved";
}
}
The problem is, when I debug the code, pnlInput.Controls shows Zero count. Please help !!
As I already answered here all dynamic controls should be reinitiated in Page's Init event, as viewstate manager values are set every request. You can check page's lifecycle.
So right now, when you do not create you control in init event, viewstates misses them while it is setting postback data, and when you do try to get values, they are equal to zeros.
Keep in mind, that you have to create the same control types with the same names.
If you have written the code to generate Dynamic Controls and if it is in the page load event use FindControl("IdofControl"); to retrive its value;
For Example,
TextBox txtInstance = (TextBox)FindControl("IdofControl");
string txtvalueinTextBox =txtInstance.Text;
Make sure that the controls are dynamically generated in all page reloads.If the controls generated on the postback is different the viewState may not restore back properly.

AutoComplete with context key in a Textbox based on two parameters?

Refer the Image, having 2 TextBox(tbxAttribute and tbxAttributeDesc).
Value will be loaded when page is loaded in tbxAttribute TextBox.In tbxAttributeDesc TextBox the end user will Fill that Data.
I have already Completed the Autocomplete Text in tbxAttributeDesc.
We are maintaining these Values in a table, Based up on the loaded tbxAttribute value their corresponding AttributeDesc will be highlight into tbxAttributeDesc Textbox
My Code be:
autoDesc = new AjaxControlToolkit.AutoCompleteExtender();
autoDesc.ID = "autoDesc" + i;
autoDesc.BehaviorID = "tbxAtribute" + i;
autoDesc.ServicePath = "itemvaluemas.asmx";
autoDesc.ServiceMethod = "GetAttributeDesc";
autoDesc.TargetControlID = tbxAttributeDesc.ID;
autoDesc.MinimumPrefixLength = 1;
autoDesc.CompletionInterval = 10;
autoDesc.FirstRowSelected = true;
autoDesc.CompletionSetCount = 30;
autoDesc.UseContextKey = true;
and also used Javscript Concept.
Refer the Below Image:
Here i need to pass condition as tbxAtribute and their Corresponding tbxAtributeDesc, based up on that tbxAbbr Value need to be highlight..
if i use ContextKey then how i pass these two textbox value in a context key..
If you have any idea please help to solve this problem.
Use ContextKey property to pass the value of textbox into GetAutoCompleteValues function.
txtbox1.Attributes.Add("onchange", "$find('BehaviourIDOftbxAttributeDesc').set_contextKey(tbxAttribute.value);");
For more information check the below links:
AJAX C# AutoCompleteExtender contextKey
http://arrao4u.wordpress.com/2010/01/14/autocomplete-extender-with-context-key/
This is the Solution which i found.
I use JavaScript:
function SetContextAbbr(formatid, itemValue, behaveid) {
var autoComplete1 = $find(behaveid);
var target = autoComplete1.get_element();
var txtformatid = document.getElementById(formatid);
var txtitemValue = document.getElementById(itemValue);
var contextkeydata = txtformatid.value + "-" + txtitemValue.value;
autoComplete1.set_contextKey(contextkeydata);
}
Use Function as
public string[] GetItemabbr(string prefixText, int count, string contextKey)
{
string[] splitvalue = contextKey.Split('-');
//code here
}
In WebService
autoabbr = new AjaxControlToolkit.AutoCompleteExtender();
autoabbr.ID = "autoabbr" + i;
autoabbr.BehaviorID = "autoabbrbehave" + i;
autoabbr.ServicePath ="itemvaluemas.asmx";
autoabbr.ServiceMethod = "GetItemabbr";
autoabbr.TargetControlID = txtItemAbbrValue.ID;
autoabbr.MinimumPrefixLength = 1;
autoabbr.CompletionInterval = 10;
autoabbr.FirstRowSelected = true;
autoabbr.CompletionListCssClass = "completionList";
autoabbr.CompletionListHighlightedItemCssClass = "itemHighlighted";
autoabbr.CompletionListItemCssClass = "listItem";
autoabbr.CompletionSetCount = 30;
autoabbr.UseContextKey = true;

How to place child controls in a certain order when binding a custom control?

What I'm trying to achieve is a custom calendar where I place events.
I've created a basic custom control which simply lists the events:
namespace MyControls
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public class Calendar : CompositeDataBoundControl
{
protected override Int32 CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
{
Int32 itemCounter = 0;
if (dataSource != null)
{
IEnumerator dataSourceEnumerator = dataSource.GetEnumerator();
while (dataSourceEnumerator.MoveNext())
{
LinkButton eventLink = new LinkButton();
eventLink.Click += new EventHandler(EventLinkClick);
HtmlGenericControl eventContainer = new HtmlGenericControl();
eventContainer.Controls.Add(eventLink);
eventContainer.TagName = "p";
this.Controls.Add(eventContainer);
if (dataBinding)
{
CalendarEvent currentEvent = (CalendarEvent) dataSourceEnumerator.Current;
eventLink.CommandArgument = String.Concat(currentEvent.Name, "ยง", currentEvent.Day.ToBinary());
eventLink.Text = currentEvent.Name;
eventLink.ToolTip = currentEvent.Description;
}
itemCounter++;
}
}
return itemCounter;
}
protected void EventLinkClick(Object sender, EventArgs e)
{
}
}
}
The control works, when I pass it a List<CalendarEvent> it displays every event's LinkButton inside its own <p />, when I click a LinkButton the EventLinkClick method gets called, and after the postback the LinkButtons are still there with their values.
However, I don't need a plain list of the event, I need to place my events inside a calendar, inside the correct day.
I create my calendar like this:
Int32 year = 2011;
Table monthTable = null;
TableRow weekRow = null;
for (DateTime day = new DateTime(year, 1, 1); day.Year == year; day = day.AddDays(1))
{
if (day.Day == 1)
{
HtmlGenericControl monthName = new HtmlGenericControl();
monthName.InnerText = CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(day.Month);
monthName.TagName = "h2";
this.Controls.Add(monthName);
monthTable = new Table();
TableHeaderRow headerRow = new TableHeaderRow();
headerRow.TableSection = TableRowSection.TableHeader;
monthTable.Rows.Add(headerRow);
for (Int32 i = 0; i < 7; i++)
{
TableHeaderCell dayOfWeekCell = new TableHeaderCell();
dayOfWeekCell.Text = CultureInfo.CurrentUICulture.DateTimeFormat.GetShortestDayName((DayOfWeek) i);
headerRow.Cells.Add(dayOfWeekCell);
}
weekRow = new TableRow();
weekRow.TableSection = TableRowSection.TableBody;
for (Int32 i = 0; i < (Int32) day.DayOfWeek; i++)
{
weekRow.Cells.Add(new TableCell());
}
}
if (day.DayOfWeek == DayOfWeek.Sunday && day.Day != 1)
{
monthTable.Rows.Add(weekRow);
weekRow = new TableRow();
weekRow.TableSection = TableRowSection.TableBody;
}
TableCell dayCell = new TableCell();
dayCell.Text = Convert.ToString(day.Day);
weekRow.Cells.Add(dayCell);
if (day.Day == DateTime.DaysInMonth(day.Year, day.Month))
{
for (Int32 i = (Int32) day.DayOfWeek; i < 6; i++)
{
weekRow.Cells.Add(new TableCell());
}
monthTable.Rows.Add(weekRow);
this.Controls.Add(monthTable);
}
}
which yields to something like this:
.
Now, how can I integrate the two things?
What I came up with is casting the dataSource parameter to IEnumerable<CalendarEvents> and after the dayCell.Text = Convert.ToString(day.Day); line I get the events of the day from the IEnumerable<CalendarEvents> through LINQ.
However, this breaks on postback because when the control is recreating itself after a postback the dataSource parameter is full of nulls, so I can't fetch the events of the day, so I can't recreate the controls.
I couldn't find anything on the net about this, and I'm completely stuck.
Am I missing (or messing) something? What should I do to achieve what I'm looking for?
Update #1
As StriplingWarrior suggested I tried to save the dataSource in the ViewState, however I failed dramatically.
What I tried is this: at the beginning of the CreateChildControls method I placed
if (dataBinding)
{
this.ViewState.Add("myDataSource", dataSource);
}
IEnumerable myDataSource = (IEnumerable) this.ViewState["myDataSource"];
and replaced every call to dataSource with myDataSource.
However, when the page post backs this.ViewState["myDataSource"] is null, and I'm back to square one.
I'm starting to regret when I decided to go with a CompositeDataBoundControl... :\
Update #2
I tried to create a new project containing only the custom control, and I rewrote it from scratch, and StriplingWarrior's suggestion worked:
if (dataBinding)
{
this.ViewState.Add("DataSource", dataSource);
}
else
{
dataSource = (IEnumerable) this.ViewState["DataSource"];
}
However, I haven't been able to pinpoit what was causing the this.ViewState["DataSource"] in the original solution.
You're running into ViewState issues. You can either disable viewstate on your control, or write the control in such a way that it saves the information it needs in ViewState, so it doesn't need to rebind to the data source on subsequent postbacks.

Categories

Resources