How to call javascript from code behind for Repeater control - javascript

There is a span element that need to load data dynamically from a Repeater control.
The problem that I encounter is only first span element can display the value. The subsequent will display blank.
I've simplify the code behind as below.
private int incre = 0;
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem ritem in FeaturedRepeater.Items)
{
HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
span.Load += new EventHandler(test);
}
}
protected void test(object sender, EventArgs e)
{
HtmlGenericControl span = (HtmlGenericControl)sender;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
incre++;
}
Javascript function in .aspx file example as below:
function timer(increment, timespan) {
var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
document.getElementById(id).innerHTML = id;
}
HTML part:
<asp:Repeater runat="server" ID="FeaturedRepeater" OnItemDataBound="FeaturedRepeater_ItemDataBound">
<ItemTemplate>
<span id='countdown' runat="server"></span>
</ItemTemplate>
</asp:Repeater>

Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);
you can't register the same key more then one time.
that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work
btw
and ; after every javascript function call.

Related

Troubles to open ajaxToolkit:ModalPopupExtender with JavaScript

I'm trying to open a ajaxToolkit:ModalPopupExtender with JavaScript but when I run my code and I call the function from the code behind this crash and show this error.
JavaScript runtime error: Unable to get property 'show' of undefined
or null reference
this is my JavaScript:
<script>
function closeChangeArea() {
$find('ModalChangeArea').hide();
}
function showChangeArea() {
$find('ModalChangeArea').show();
}
</script>
and this is my code:
protected void Btn_Click_Ch_Area(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label ToolChange = (Label)gr.FindControl("Lbl_toolg");
Txt_Tool_Reasign.Text = ToolChange.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showChangeArea();", true);
}
this is my ModalPoupExtender
<ajaxToolkit:ModalPopupExtender
ID="ModalChangeArea"
runat="server"
TargetControlID="hid"
PopupControlID="ChangeArea"
RepositionMode="RepositionOnWindowResizeAndScroll"
DropShadow="true"
PopupDragHandleControlID="moveArea">
</ajaxToolkit:ModalPopupExtender>
In asp.net control id is dynamically appended with container, in that case you will not get the control using $find to get control use clientid of asp.net control or set ClientIdMode = "Static".
Try below code to access element.
$find('<%= ModalChangeArea.ClientID %>').show();
$find('<%= ModalChangeArea.ClientID %>').hide();

change date label by user

I'm using C#.net to program a reservation system
I want to let the user change date through the arrows as shown on the picture (please click on the link)
date image
I have done from displaying the current date on the screen but I just don't know how to let the user use the arrows to change the dates
these are the html codes:
<asp:Label ID="lblServerDateTime" runat="server" CssClass="auto-style13" style="font-size:30px;" />
and these are the C# code
protected void page_load(object sender, EventArgs e)
{
lblServerDateTime.Text = DateTime.Now.ToString("M");
}
This snippets may help you:
Aspx
<asp:Button Text="Down" ID="btnDown" runat="server" OnClick="btnDown_Click" />
<asp:Label ID="lblServerDateTime" runat="server" CssClass="auto-style13" Style="font-size: 30px;" />
<asp:Button Text="UP" ID="btnUp" runat="server" OnClick="btnUp_Click" />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblServerDateTime.Text = DateTime.Now.ToString("dd MMMM");
calCurrentDay.SelectedDate = DateTime.Now;
// Sets current date on initially.
}
}
protected void btnUp_Click(object sender, EventArgs e)
{
//Up button click will increase the date by one day
DateTime.TryParse(lblServerDateTime.Text, out d);
d = d.AddDays(1);
lblServerDateTime.Text = d.ToString("dd MMMM");
calCurrentDay.SelectedDate = d;
}
protected void btnDown_Click(object sender, EventArgs e)
{
//Up button click will decrease the date by one day
DateTime d;
DateTime.TryParse(lblServerDateTime.Text, out d);
d = d.AddDays(-1);
lblServerDateTime.Text = d.ToString("dd MMMM");
calCurrentDay.SelectedDate = d;
}

Accessing dynamic created html checkboxes in code behind

I am dynamically creating my html checkboxes at runtime using javascript/jquery like this. It's using the Jquery bootgrid.
isAssigned: function (column, row) {
if (row.isAssigned == "True" || row.isAssigned == "true") {
return "<input id='chk" + row.id + "' type='checkbox' name='chkMarks' checked='" + row.isAssigned + "' />";
}
else {
return "<input id='chk" + row.id + "' type='checkbox' name='chkMarks'/>";
}
}
What I need to do is somehow get the values in my submit buttons click event in the aspx.cs code behind. I cannot runat="server" these controls because the id is not added until after the page has loaded. I need to get the id's and whether they are true or false.
I was wondering if anyone knew the best approach for me to get these values in something like this.
protected void myTester_Click(object sender, EventArgs e)
{
var values = Request["chkMarks"].ToString();
}
You almost had it! You need to use Request.Form instead of just Request. That should give you access to all your DOM elements.
var values = Request.Form["chkMarks"].ToString();
Here is some more information on it: https://msdn.microsoft.com/en-us/library/system.web.httprequest.form(v=vs.110).aspx
Request.Unvalidated["chkMarks"]
can also be useful depending on what the value of this field is.
I did it using JSON in the end using a postback so not asynchronous which is hopefully useful to someone.
function BuildJSON() {
var jsonObj = [];
jQuery("input[name='chkMarks']").each(function () {
item = {}
item["id"] = this.id;
item["isAssigned"] = this.checked;
jsonObj.push(item);
});
var json = JSON.stringify(jsonObj);
$('#<%= hiddenMarksID.ClientID %>').val(json);
}
In the code behind I attached an event to button and picked up the JSON like so...
protected void btnSubmitMarks_Click(object sender, EventArgs e)
{
string json = hiddenMarksID.Value;
List<ChkMark> chkMark = new JavaScriptSerializer().Deserialize<List<ChkMark>>(json);
Here is the POCO...
public class ChkMark
{
public string id { get; set; }
public bool isAssigned { get; set; }
}

JavaScript function in c# asp.net button click event not working

I'm in a asp.net c# project. I want to print employees card with bar code. So I write a html tag in string variable call htmlCon and it will bind a DIV tag in client side (get all employees and loop it for print one by one).
it work fine. but inside the htmlCon variable has java script function it will not run in loop.
protected void btnGenarate_ClickEvent(object sender, EventArgs e)
{
......
foreach (var item in empDetails)
{
htmlCon += ..........+
"<script>"+
"$(document).ready(function ()"+
"{ $('#barcode').JsBarcode('"+ item.EmployeeNo + "', { width: 1, height: 30 }); });"+
"</script>" +
"<img id='barcode' class='barcode'/>" +
"........................................"+
}
}
this code comes with bar code and it will print first round in the loop..I want to run all employees for get bar code.
You are generating many images with the same ID, you should generate a new id for each loop iteration. I would also recommend using a StringBuilder instead of a bunch of string concatenations:
protected void btnGenarate_ClickEvent(object sender, EventArgs e)
{
StringBuilder htmlCon = new StringBuilder();
for (int i = 0; i < empDetails.Count; i++)
{
htmlCon.AppendFormat("<script>$(document).ready(function () { $('#barcode{0}').JsBarcode('{1}', { width: 1, height: 30 }); });</script><img id='barcode{0}' class='barcode'/>",
i.ToString(), empDetails[i].EmployeeNo);
htmlCon.Append("........................................");
}
//To Use StringBuilder value
string html = htmlCon.ToString();
}

ASP.NET: HtmlGenericControl <DIV> - refresh

I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}

Categories