ASP finds dropdown with 0 elements but the elements are there - javascript

I'm using ASP to look for the selected value in a dropdown box. The dropdown box choices are generated at load time. Here is the JavaScript for that:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
}
And it looks like this:
Looks fine to me. Then I checked the HTML out too just to be sure:
That looks great too. Now here is where the issue comes up. When I press submit this delegate fires in C# (still only testing while making this):
void Activity_Submit_Click(object sender, EventArgs e)
{
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
And when I debug this it stops at department saying that it's malformed. Looking at department_dropdown.Value in the immediate window turns up an empty string and the dropdown itself has 0 children.
Why would this return an empty response when the list is clearly there? How would I go about fixing this?

The client-side items won't get posted back to the server like this.
The easiest way is to Serialize the array as Json, put it in a hidden input element's value :
In your markup:
<asp:HiddenField runat="Server" ID="department_dropdown_items" cssclass="department_dropdown_items" />
<asp:HiddenField runat="Server" ID="department_dropdown_selected" cssclass="department_dropdown_selected" />
Your Javascript:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
$(".department_dropdown_items").text(JSON.Stringify(data));
}
$(document).ready(function() {
$("form").submit(function(e) {
$(".department_dropdown_selected").text( $("#department_dropdown").value);
});
});
then use it in the code behind:
void Activity_Submit_Click(object sender, EventArgs e)
{
string[] data = new JavascriptSerializer().Deserialize<string[]>(department_dropdown_items.Value);
string selectedValue = department_dropdown_selected.Value;
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
The code is not tested. Tell me if it's not working :)

So I ended up doing the following:
Make a Hidden asp element called department_dropdown_selected_value
Then in a Script tag I made the following function:
.
function GetDepartmentDropdownValue(sel) {
var hidden_field = document.getElementById('department_dropdown_selected_value');
hidden_field.value = sel.value;
}
Then in my HTML I did this: <select class="form-control" id="department_dropdown" onchange="GetDepartmentDropdownValue(this)">
Then I can just simply do this in C#: int department = Int32.Parse(department_dropdown_selected_value.Value);

Related

How to select IDs of inputs created dynamically?

What i'm trying to do :
The working concept in JS :
In a basic form, i'm trying to reproduce this in a C# app
To clarify, user has to be able to choose how many parts there is (and name each part).
=> Example : My item has two parts, part_1 = "morning" and part_2 = "afternoon".
In order to reproduce that, i've done the following :
form.aspx :
<myform>
<asp:TextBox CssClass="form-control" runat="server" type="number" ID="parts_counter" />
<div id="content" runat="server"></div>
</myform>
=> Why : The value of parts_counter is then meant to be read and with a javascript block (i know...) i create the inputs dynamically
javascript_form.js :
let counter = document.getElementById('parts_counter');
let content = document.getElementById('content');
counter.addEventListener('change', function (e) {
if (counter.value == 0) {
content.innerHTML = "";
} else {
content.innerHTML = "";
for (let i = 0; i < counter.value; i++) {
content.innerHTML +=
"<input type='text' id='part_" + i + "' placeholder='Ex : Part name'/><br>";
// ---------------------^^^^^^^^^^^^
// THIS IS THE PART I WANT TO BE ABLE TO READ IN C # Codebehind
}
}
})
form.aspx.designer.cs :
protected global::System.Web.UI.WebControls.TextBox part_0;
protected global::System.Web.UI.WebControls.TextBox part_1;
protected global::System.Web.UI.WebControls.TextBox part_2;
protected global::System.Web.UI.WebControls.TextBox part_3;
protected global::System.Web.UI.WebControls.TextBox part_4;
=> Why : I tried to pre-register generated IDs, as there's no reason to have more than 5 parts in user scenario.
form.aspx.cs :
for (var i = 0; i < Convert.ToInt32(parts_counter.Text); i++)
{
var nomPartie = "partie_" + i;
var textBoxPartie = new TextBox();
textBoxPartie.ID = nomPartie;
// Do something for each
i++;
}
=> Why :
I read value of the counter,
I loop for each value to do a server-side action
I (over) looked at some solutions on CodeProject, SO, ASPSnippets and i'm sure i've thought of this the wrong way, could you please tell me if there is a specific way to generate inputs and to get their IDs afterwards in codebehind ?
Every pennies are welcome

Column sum of multiple columns of dynamic gridview using Javascript

I have a Dynamic asp Gridview with all columns as template feild TextBox. The columns of the Gridview are also dynamic and column count may vary everytime.
Please find code below
public void FillPoDetails()
{
DataTable dt = new DataTable();
dt = pmdata.createdatatable(int.Parse(Session["OurStyleid"].ToString()), int.Parse(Session["PoPackid"].ToString()));
GenerateTable(dt.Columns.Count, dt.Rows.Count,dt);
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
TemplateField bfield = new TemplateField();
//Initalize the DataField value.
bfield.HeaderTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Header, col.ColumnName);
//Initialize the HeaderText field value.
bfield.ItemTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GrdDynamic.Columns.Add(bfield);
}
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label();
//Allocates the new label object.
lbl.Text = _columnName;
lbl.CssClass = "Headerclass";
//Assigns the name of the column in the lable.
container.Controls.Add(lbl);
//Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox();
//Allocates the new text box object.
tb1.DataBinding += new EventHandler(tb1_DataBinding);
//Attaches the data binding event.
tb1.Columns =6;
//Creates a column with size 4.
// tb1.Width = System.Web.UI.WebControls.Unit.Percentage(100);
tb1.Width = 100;
tb1.Wrap = true;
tb1.ID = "txt_" + _columnName;
if(_columnName== "ColorTotal")
{
tb1.CssClass = "ColorTotal";
}
else if (_columnName == "Color")
{
tb1.CssClass = "Color";
}
else
{
tb1.CssClass = "txtCalQty";
tb1.Attributes.Add("onkeypress", "return isNumberKey(event,this)");
tb1.Attributes.Add("onkeyup", "sumofQty(this)");
}
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
}
}
And inorder to get the row total I had added a Javascript function on keydown event and its working clearly
//calculate the sum of qty on keypress
function sumofQty(objText) {
var cell = objText.parentNode;
var row = cell.parentNode;
var sum = 0;
var textboxs = row.getElementsByClassName("txtCalQty");
for (var i = 0; i < textboxs.length; i++)
{
sum += parseFloat(textboxs[i].value);
}
var textboxtotalqtys = row.getElementsByClassName("ColorTotal");
textboxtotalqtys[0].value = sum.toString();
}
And the result is Like below
can anyone please help me in finding out the sum of each columns(all same cssclass).and display it in the Sizetotal row because I am not able to loop through columns
I would give every textbox a row id and a column id through html5 data attributes. and in javascript (jQuery) filter the textboxes through column id.
example:
..
var sum = 0;
$( "input[data-column-id='" + selectedColumnId + "']" ).each(function( index )
{
sum += parseFloat($( this ).val() );
});
..
By the way, use jQuery. its amazing.
Not sure about your requirement but this may help you, After binding data to grid, once again loop through the column list
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
int rowIndex=2;
GrdDynamic.FooterRow.Cells[1].Text = "Total";
GrdDynamic.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
foreach (DataColumn col in dt.Columns)
{
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>(col.Caption));
GrdDynamic.FooterRow.Cells[rowIndex++].Text = total.ToString("N2");
}
There is a very simple way.
Add Footer and Label to each Column, Then do calculations from database side best is use LINQ and Group by, find footer Label Controls for each column and Bind values to those Footer's Label Control, in this way your UI will have less load.
See here for code:
.ASPX Page in Grid:
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Literal ID="ltrlTotal" Text='<%#Eval("Total") %>' runat="server"> </asp:Literal> // For Sub Total
</ItemTemplate>
<FooterTemplate>
<strong><asp:Literal ID="ltrlGrandTotal" runat="server"> // This is Grand Total
</asp:Literal></strong>
</FooterTemplate>
</asp:TemplateField>
C# Code:
var searchResult = soService.SearchResult(companyId);
var grandTotal = searchResult.Select(so => so.Total).Sum();
searchResult.All(aa => aa.GrandTotal == grandTotal);
gridSo.DataSource = searchResult;
gridSo.DataBind();
if (searchResult.Count > 0)
{
Literal ltrlGrandTotal = gridSo.FooterRow.FindControl("ltrlGrandTotal") as Literal;
if (ltrlGrandTotal != null)
ltrlGrandTotal.Text = string.Format("Grand Total : $ {0}", grandTotal);
}

calling a JavaScript function on Asp.net textBox

Please help! i have been trying to call this function on my Asp.net textbox to format users input while typing.
function format(number) {
var decimalSeparator = ".";
var thousandSeparator = ",";
var result = String(number);
var parts = result.split(decimalSeparator);
if (!parts[1]) {
parts[1] = "00";
}
result = parts[0].split("").reverse().join("");
result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);
parts[0] = result.split("").reverse().join("");
return parts.join(decimalSeparator);
}
// i tried using onkeyup, it didnt work
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onKeyup="javaScript: format(this);"></asp:TextBox>
// also i tried using onChange, it didnt work.
<asp:TextBox ID="txtTransport" runat="server" CssClass="TextBoxes" onChange="javaScript:format(this);"></asp:TextBox>
protected void Page_Load(object sender, EventArgs e)
{
txtTransport.Attributes.Add("onKeyup", "javaScript: format(this);");
}
You can do it directly from javascript, not in codebehind !
var el = document.getElementById("<%= txtTransport.ClientID %>");
el.onkeyup = function(e) {
// Do stuff
};
But I think your function is logicaly wrong. Try it anyway. Your ID of a server side control is not exactly the same you write in the code, for get the real ID you can use <%= txtTransport.ClientID %>.

Findcontrol for label in gridview using javascript

I have a gridview which has some templatefield. At cell5 i have a label which is the input for database. but not all the labels in all the rows contains the value. its based on the click event of an editTemplateField. I have vb.net code for accessing that label inside the gridview. but i want to get it by javascript. following is the sample vb.net code and javascript that i have tried so far.
For Each i as gridViewRow in gridview.Rows
Dim lnk as linkbutton = CType(i.FindControl("del"),LinkButton)
If lnk.ForeColor = Drawing.Color.Red
pid = CType(gridview.Rows(i).FindControl("lblposid"), Label).Text
End If
Next
javascript:
for (var i = 0; i < grid.rows.length-1; i++) {
if(grid.rows[i].cells[1].style.color == "red")
pid = grid.rows[i].cells[5].innerHTML;
}
vb.net works . but javascript is not working. i dont know how to make it in javascript.Thanks in advance]
Note: The template field's visible is "False" also.
I found my own solution now.
for (var i = 1; i < grid.rows.length; i++)
{
var links = grid.rows[i].getElementsByTagName("a");
if(links[1].style.color=="red")
{
var spanlist = grid.rows[i].getElementsByTagName("span");
pid=spanlist[1].innerHTML;
links[1].style.color="blue";
}
}

passing dynamically created ASP.NET controls to Javascript

I'm dynamically generating a textbox and a dropdownlist in my ASP.NET web app table row, I want to change value of textbox based on dropdownlist selectedindex using javascript, but I don't know how to pass these dynamically created controls to my Javascript function.
TextBox t = new TextBox();
tc.Controls.Add(t);
tr.Cells.Add(tc);
tc = new TableCell();
DropDownList ddl = new DropDownList();
ddl.Attributes.Add("onChange", "return OnFoodChange(this," + t + ");");
tc.Controls.Add(ddl);
I pass 'this' instead of my combobox, and it works fine, but textbox is not detected in my following javascript function:
function OnFoodChange(myCmb,myTxt) {
try{
var q = document.getElementById('<%= HFFoodPrice.ClientID %>').value.toString();
var q2 = q.split(';');
alert(myCmb.selectedIndex.toString());
alert(document.getElementById(myTxt.value));
for (var j = 0; j < q2.length; j++) {
if (q2[j] != '') {
var q3 = q2[j].split(',');
{
}
}
}
}
catch(err)
{
alert(err.message);
}
}
what is the correct way of passing dynamically created controls to a javascript function? should I set controls ID in my codebehind?
In C#:
ddl.Attributes.Add("onChange", "return OnFoodChange(this," + t.ClientID + ");");
in Javascript, try this:
alert(document.getElementById(myTxt).value);

Categories