C# errors running javascript and getting cell content - javascript

I'm trying to make a graph with the content in a GridView, and now I have this codes:
string js0 = #"var data = {}; CarregarGrafico(data);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Graph0L", js0, true);
var i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
string periodo = "" + row.Cells[0].Text + "/" + row.Cells[1].Text + "";
string prevReceb = row.Cells[6].Text.ToString();
string totalReceb = row.Cells[10].Text.ToString();
string js1 = #"myBarChart.addData([{1}, {2}], '{0}');";
js1 = js1.Replace("{0}", periodo).Replace("{1}", prevReceb).Replace("{2}", totalReceb);
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Graph1L", js1, true);
i++;
if (i >= 10) break;
}
But I'm dealing with some problems:
Script aren't appearing at the page
I can't get the prevReceb and totalReceb values because it was in a <span> tag. How can I use only text into span of the cell?
Please, help me, thanks.

Related

html Text editor value is not getting saved

I want to use a text editor in my page.the editor that I have used is
"Responsive-WYSIWYG-Text-Editor-with-jQuery-Bootstrap-LineControl-Editor"
This my div tag on which I have applied the text editor and like this I have 5 more div tags with different id's on which I have used this editor
<div rows="" cols="" class="form-control Editor-editor" type="text" id="achievementresponsiblity" detail="industry" indus="indus" placeholder="Responsibilities And Achievements" name="Responsibility"></div>
when I am trying to save the content or text written/entered in these divs it's not saving any data. I mean it's not taking the value written in it. Json that I have created for it is as follows
$("#Projectssave").click(function () {
var remarks = 0;
jsondata = "";
if ($('[type="checkbox"][industry="project"]').prop("checked") == true) {
remarks = 1;
}
jsondata += "'ProjectTypeId':'5',"
jsondata += "'Remark':'" + remarks + "',"
jsondata += "'Responsibility':'" + $("#achievementresponsiblity").text().replace(/'/g, "&apos;").replace(/"/g, "&Double;").replace(/</g, "<").replace(/>/g, "&tg;").replace(/\\/g, """) + "',";
$.each($('input[detail="Projects"][type="text"],input[detail="Projects"][type="number"],textarea[detail="Projects"],select[detail="Projects"]'), function () {
jsondata += "'" + $(this).attr('name') + "':'" + $(this).val().replace(/'/g, "&apos;").replace(/"/g, "&Double;").replace(/</g, "<").replace(/>/g, "&tg;").replace(/\\/g, """) + "',";
});
jsondata = jsondata.substr(0, jsondata.length - 1);
jsondata = '{' + jsondata + '}';
saveindustrlial(jsondata, $(this).attr("savetype"), "Projects Details");
});
but it just save null data in it. I don't know how to deal with it I am done with trying almost everything.
You can find some documentation about the LineControl editor here: https://github.com/suyati/line-control
To get the text from the editor:
$("#achievementresponsiblity").Editor("getText");
To set the text in the editor:
$("#achievementresponsiblity").Editor("setText", "Your text value");

Dynamically generated html, document.getElementByID returns null

I am generating an html table dynamically in my code behind file
protected void PopulateMemberTable()
{
var guid = "";
string[] selectedColumns = new[] { "MEMBID", "MEMBER_NAME", "BIRTH", "IPA", "HPNAME" };
if (Session["guid"] != null)
guid = Session["guid"].ToString();
StringBuilder html = new StringBuilder();
DataTable dt = MemberSearch(guid, membFirst.Text.ToString(), membLast.Text.ToString(), membDob.Text.ToString(), membId.Text.ToString());
if (dt != null)
{
DataTable new_dt = new DataView(dt).ToTable(false, selectedColumns);
html.Append("<table class='table table-hover data-table'>");
html.Append("<thead>");
html.Append("<tr>");
foreach (DataColumn column in new_dt.Columns)
{
html.Append("<th>");
switch(column.ColumnName.ToString())
{
case "MEMBID":
html.Append("Member ID");
break;
case "MEMBER_NAME":
html.Append("Member Name");
break;
case "BIRTH":
html.Append("DOB");
break;
case "IPA":
html.Append("IPA");
break;
case "HPNAME":
html.Append("Health Plan");
break;
}
html.Append("</th>");
}
//btn column (no header)
html.Append("<th></th>");
html.Append("</tr>");
html.Append("</thead>");
html.Append("<tbody>");
var counter = 0;
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
html.Append("</tbody>");
html.Append("</table>");
}
else
html.Append("<div class='alert alert-danger' role='alert'>No Members Found</div>");
membTable.Controls.Add(new Literal { Text = html.ToString() });
}
The table is generated just fine, but now I am trying to call some server side code when a row is clicked
foreach (DataRow row in new_dt.Rows)
{
counter++;
string btnId = "\"" + "<%btnMembGrid" + counter.ToString() + ".ClientId%>" + "\"";
html.Append("<tr onclick='document.getElementById(" + btnId + ").click()'>");
var btnValue = new StringBuilder();
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
html.Append("<td><asp:button runat='server' OnClick='selectMember' CssClass='btn btn-default' style='display:none' value = '"
+ btnValue.ToString() + "' id= 'btnMembGrid" + counter.ToString() + "'/></td>");
html.Append("</tr>");
}
I attempted to accomplish this task by placing a hidden <asp:Button/> in each row and then adding a corresponding onclick attribute to each <tr> tag
This is how the generated html looks like in the dev console
However when I attempt to click the row I get the following error message
I am having a hard time understanding what exactly I'm doing wrong. I'd appreciate some input, or possibly even an alternative approach.
You can use jquery and use the delegation model to handle click on dynamic elements. if for example you have some html like
<div id="dynamicname'></div>
then use
the jquery code snippet
$(document).on('click','#dynamicname',function(){
//handle your event here
});
dynamic html should always be handled by delegation model. And you can use
var dynamic_name="#"+getYourDynamicRowName;//variable for dynamic id's of dynamic html element
$(document).on('click',dynamic_name,function(){
//handle your event here
});
As per my experience we can not use asp tag while you are creating dynamic HTML.
If you see your code of dev console you can see that controls are not rendered properly..rendered with asp tag..
To achieve it you can use javascript/Jquery to call server side function.
<input type="button" ID="btn" runat="server" onclick="fn();" />
And in your javascript:
fn = function(){
__doPostBack("<%=btn.ClientID%>", "");
}
And in your code:
`
protected override void btnEvent(IPostBackEventHandler source, string eventArgument)
{
//call the button event
//base.btnEvent(source, eventArgument);
if (source == btn)
{
//do some logic
}
}
After figuring out that passing an <asp:button/> as a string wasn't going to work, I took an alternative approach.
In populateMemberTable()I added an href attribute to the first column in each row
var href = true;
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
if (href)
{
href = false;
html.Append("<a href='/default.aspx?guid=" + Session["guid"] + "&membid=" + row[column.ColumnName] +"'>");
html.Append(row[column.ColumnName]);
html.Append("</a></td>");
}
else
{
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
}
And then I saved the membId as a session variable in Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
//save guid (http://url.com?guid=xxxxxx) as session variable
Session["guid"] = Request.QueryString["guid"];
var membId = Request.QueryString["membid"];
if (membId != null)
{
Session["membid"] = membId;
}
}
It might not be the most elegant solution, but it got me what I needed and was straightforward to implement. Thanks for the input everyone!

Getting the ID in of an ASP drop down list from client side

What I'm trying to do is get one of my drop down list to change its contents whenever the selected item in another one cahnges. I have this code in my aspx file:
function ModifyDDLItems(id1, id2)
{
var ddlcontrolShown = document.getElementById(id1);
var ddlcontrolHidden = document.getElementById(id2);
if (ddlcontrolShown.options[ddlcontrolShown.selectedIndex].value == "DD1")
{
//Get number of items of hidden ddl
var length = ddlcontrolHidden.options.length;
//Clear items of shown ddl
ddlcontrolShown.options.length = 0;
//Add itmems of hidden ddl to shown ddl
for (i = 0; i < length; i++)
{
ddlcontrolShown.options.add
var newoption = document.createElement("option")
newoption.text = ddlcontrolHidden.options[i].text;
newoption.value = ddlcontrolHidden.options[i].text.value;
}
}
}
Now, i give it the front end ID's thru this:
protected void SetDD1ConfItems(GridViewRow gvRow, DataSet BaseConfItems)
{
DataView dvConfType = new DataView(BaseConfItems.Tables[0]);
DataSet dsTemp = BaseConfItems.Clone();
DropDownList ddlConfType2 = (DropDownList)form1.FindControl("ddlConfType2");
DropDownList ddlBA = (DropDownList)gvRow.FindControl("ddlBA");
DropDownList ddlConfType = (DropDownList)gvRow.FindControl("ddlConfType");
dvConfType.RowFilter = "ref_code = 'FAX' or ref_code = 'EEX' or ref_code = 'EPD'";
dsTemp.Tables.Clear();
dsTemp.Tables.Add(dvConfType.ToTable());
ddlConfType2.DataSource = dsTemp;
ddlConfType2.DataBind();
//ddlBA.Attributes["onchange"] = "function GetDDLD(" + ddlConfType.ClientID + ", " + ddlConfType2.ClientID + ") {ModifyDDLItems(id1, id2);}";
ddlBA.Attributes.Add("onchange", "ModifyDDLItems('" + ddlConfType.ClientID + "', '" + ddlConfType2.ClientID + "')");
}
When I run it, VS keeps on telling me that id1 and id2 are both null, it seems the id's aren't passed to the client properly.
I think you have code wrongly, the first mistake i found at a glance is,
You cannot find the controls inside gridview by using
gvRow.FindControl("ddlBA");
There may be multiple rows in GridView, so you have to find your controls in each Row as all of them will have different ClientIDs. First to try to replace the below code
gvRow.Rows[RowIndex].FindControl("ControlID");
ALso, it should be written in the some kind of loop in order to find the RowIndex value of the Grid.
Describe your exact requirement in brief. So, that i can help you in writing the proper code.

Request.Form.FindAllKeys Not Working In IE8

I am creating textboxes on my page client side like so..
var _text = document.createElement("input");
_text.setAttribute("type", "text");
_text.setAttribute("id", "txtAsName" + num);
_text.setAttribute("name", "txtAsName" + num);
In the server side code I retrieve the ids of any textboxes on the form (you could add txtAsName1, txtAsName2, txtAsName3 and then remove txtAsName2 all client side so its important in my case to grab any textboxes on left on the form during a postback)
I am getting the ids of the remaining textboxes on the server side using this:
string[] allFormKeys = Request.Form.AllKeys;
foreach (string key in allFormKeys)
{
Response.Write("Key Name: " +key + "<br/>");
if (key.StartsWith("txtAsName"))
{
txtBoxes.Add(key);
}
}
In firefox this works fine but in IE8 Request.Form.AllKeys returns no textboxes! I can see this via the Response.Write and in firefox I get the textboxes.
I checked if maybe there is 2 form tags in the html but that isnt the case
Is it possible that you are forgetting to append the newly created element to your form?
<script>
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("name", "testing123");
input1.setAttribute("value", "i like cake");
document.getElementById("formid").appendChild(input1);
</script>
You don't say in your question what you add the text input elements to. I used your code, made sure I was adding the text input fields as children somewhere inside the form element, and I'm definitely seeing them get posted back to the server:
<div id="testDiv"></div>
<br />
<asp:Label ID="Label1" runat="server" />
<asp:Button runat="server" />
<script type="text/javascript">
var num = 0;
var _text = document.createElement("input"); _text.setAttribute("type", "text"); _text.setAttribute("id", "txtAsName" + num); _text.setAttribute("name", "txtAsName" + num);
testDiv.appendChild(_text);
num++;
_text = document.createElement("input"); _text.setAttribute("type", "text"); _text.setAttribute("id", "txtAsName" + num); _text.setAttribute("name", "txtAsName" + num);
testDiv.appendChild(_text);
num++;
_text = document.createElement("input"); _text.setAttribute("type", "text"); _text.setAttribute("id", "txtAsName" + num); _text.setAttribute("name", "txtAsName" + num);
testDiv.appendChild(_text);
</script>
and
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.AllKeys.Length > 0)
{
string keys = string.Join(", ", Request.Form.AllKeys);
Label1.Text = string.Format("Found {0} keys: {1}", Request.Form.AllKeys.Length, keys);
}
else
{
Label1.Text = "Form.AllKeys.Length == 0";
}
}
When I run this and then click the button, the label shows:
Found 6 keys: __VIEWSTATE, __EVENTVALIDATION, txtAsName0, txtAsName1, txtAsName2, ctl00$MainContent$ctl00
I'm using IE8.
Look into the page html generated. There might be a possibility of improper html markup been generated from server. i.e., some html tags have not been closed properly with close tag.

getting the value of a row in a gridview after selecting its checkbox using javascript - vb- to avoid refreshing the page at each select

I have aspx gridview with checkbox on evryrow, what is required is whenever we check any of the rows, a query should be launched to change the specific agent -each row consist of agentID, Pass, Status- to Paid Status. using javascript
What I need to know is how to loop to get the Checked row and get the ID of the row checked so that I can get THe ID of the Agent in thos row so that I can update its status.using javascript
I found something similar on stackflow:
Thank you
Get GridView selected row DataKey in Javascript
But it is not my case, what is needed is at the check of a checkbox a javascript function should launch through which I could update the selected row in grid view after having the index of this row and this all to avoid refreshing the page.
Regards
you could try like this.....for finding the row index ...
Private Function getCellControl(ByVal , As rowIdx, ByVal Unknown As colIdx) As function
Dim gridCell As var = getGridColumn(rowIdx, colIdx)
Dim type As var = Nothing
Dim typePos As var
Dim ctrId As var
Dim idPos As var
Dim delPos As var
Dim inHTML As var
Dim buf As var
Dim chkStatus As var
Dim statPos As var
If (Not (gridCell) Is Nothing) Then
inHTML = gridCell.innerHTML
typePos = inHTML.indexOf("type")
If (typePos > 0) Then
typePos = (typePos + 5)
buf = inHTML.substring(typePos)
delPos = buf.indexOf(" ")
If (delPos > 0) Then
type = inHTML.substring(typePos, (typePos + delPos))
If (type = "checkbox") Then
idPos = inHTML.indexOf("id")
If (idPos > -1) Then
idPos = (idPos + 3)
ctrId = inHTML.substring(idPos, (typePos - 5))
End If
statPos = buf.indexOf(" ")
If (statPos > -1) Then
buf = buf.substring((statPos + 1))
delPos = buf.indexOf(" ")
chkStatus = buf.substring(0, delPos)
End If
End If
End If
End If
End If
Return ctrId
End Function
You could do this with jQuery:
$("#<%=GridView1.ClientID%> input[type='checkbox']").click(function(){
if ($(this).is(":checked")){
alert($(this).closest("tr").attr("id"));
}
});

Categories

Resources