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();
}
Related
I'm having an issue with the functions to be called not firing off.
I have moved from hardcoding the buttons on HTML, to using the add controls method in the cs; and I have shifted from using Button and HtmlButton to using LinkButton. However none of these seem to work. In Onserverclick and onclick not work Anup Sharma recommends using the LinkButton, and Keyvan Sadralodabai indicates that if the runat="server" is displayed in the insect element, then he control was set up wrong.
So here's a stripped down simplified version of what I'm working with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public partial class backCodeExper : System.Web.UI.Page
{
protected void saveRecord(string recordID, string buttonId, string dropdownId)
{
PlaceHolder db = Page.FindControl("TestingCS") as PlaceHolder;
HtmlTable tbl = db.FindControl("TestTable") as HtmlTable;
HtmlTableRow tr = tbl.FindControl("TheRow") as HtmlTableRow;
HtmlTableCell tc = tr.FindControl("TheCell2") as HtmlTableCell;
DropDownList ddl = tc.FindControl(dropdownId) as DropDownList;
var status = ddl.SelectedValue.ToString();
HttpContext context = HttpContext.Current;
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost; Database********; User=********; Password=********; Port=3306";
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "updatetesttable";
cmd.Parameters.AddWithValue("#param", status);
cmd.ExecuteNonQuery();
}
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable myTable = new HtmlTable();
myTable.ID = "TestTable";
myTable.BorderColor = "teal";
myTable.BgColor = "black";
TestingCS.Controls.Add(myTable);
HtmlTableRow newRow;
HtmlTableCell cell;
DropDownList DropList;
LinkButton saveButton;
newRow = new HtmlTableRow();
newRow.ID = "TheRow";
cell = new HtmlTableCell();
cell.ID = "TheCell1";
DropList = new DropDownList();
DropList.ID = "StatusDD";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("A", "1"));
DropList.Items.Add(new ListItem("B", "2"));
DropList.Items.Add(new ListItem("C", "3"));
cell.Controls.Add(DropList);
newRow.Cells.Add(cell);
cell = new HtmlTableCell();
cell.ID = "TheCell2";
cell.BgColor = "black";
saveButton = new LinkButton();
saveButton.ID = "saveButton";
saveButton.CommandName = "saveRecord";
saveButton.CommandArgument = "'1A',this.id,'StatusDD'";
saveButton.BackColor=Color.Green;
saveButton.ForeColor=Color.Cyan;
saveButton.BorderColor=Color.Maroon;
saveButton.Text = "Save";
saveButton.Visible = true;
cell.Controls.Add(saveButton);
newRow.Cells.Add(cell);
myTable.Rows.Add(newRow);
}
}
It loads the screen just fine with the simple dropdown and with the (unstylish) button (frankly the HtmlButton looks much nicer, but I'm aiming for functionality first).
When I select an item from the dropdown and then click save, the screen appears to refresh, keeping the value of the dropdown the same as that which was selected. However, when I check the database, the procedure hasn't fired. Additionally I cannot get this code segment Response.Write("<script>alert('Hello');</script>"); to execute when placed in the method/function saveRecord.
Furthermore, when I run the debugging mode and put break points in saveRecord, none of them are hit.
After inspecting element, this is what I get:
InspectElementResults
Any suggestions? What am I missing?
If I don't use LinkButton (or Button/HtmlButton with onServerClick) then I get errors saying the function isn't defined - which makes since as the function/method is define on the aspx.cs not the aspx within JS script tags.
I've got it figured out. At least, it is functional.
I was trying to set the function to pass the values I want in the format I wanted, but apparently the when you set up a LinkButton, it prefers the object and Event Args as parameters, and the object is the ListButton itself, so if that ListButton object holds the values you need in its attributes, then when the function is called you parse out the attributes you need. There's likely a better way than to assign the two values I need to CommandName and CommandArgument, but this works. (I had thought of using .Attributes.Add("ROW_ID","1a") and .Attributes.Add("DD_ID","StatusDD") ... but couldn't initially figure out how to retrieve those values from the sender object...to be investigated later, in the meantime, rolling forward with a functional solution.
...
protected void saveRecord(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string ROW_ID = (string)lb.CommandName;
string DD_ID = (string)lb.CommandArgument;
Response.Write("<script>alert('Hello');</script>");
...
}
protected void Page_Load(object sender, EventArgs e)
{
...
saveButton.CommandName = "1a";
saveButton.CommandArgument = "StatusDD";
saveButton.Click += new EventHandler(saveRecord);
...
}
}
I am trying to scrape the web page with C# and I am using HtmlAgilityPack it works good for me, but I got an issue with this website when I need to scrape data from another page of product list. Because link doesn't have page number so I cannot access it by changing link. I found out that page is changed by javascript "__doPostBack" function which doesn't changes the link, just reloads the page, and loads the data.
This is my code for scraping code and price of the product in this web site, however there are more products in other page e.g 2, 3, 4, 5... I need to scrape data from all of these. On other websites I can do just simply passing link to web.Load("Link"); and it works well because link is changing when you change page of product list. In this example link is not changing when other page of the list is selected.
public class CodeAndPrice
{
public string Code { get; set; }
public string Price { get; set; }
}
public partial class Form1 : Form
{
DataTable table;
HtmlWeb web = new HtmlWeb();
public Form1()
{
InitializeComponent();
InitTable();
}
private void InitTable()
{
table = new DataTable("DataTableTest");
table.Columns.Add("Code", typeof(string));
table.Columns.Add("Price", typeof(string));
dataGridView.DataSource = table;
}
private async Task<List<CodeAndPrice>> DataScraping (){
var page = await Task.Factory.StartNew(() => web.Load("https://www.kilobaitas.lt/Kompiuteriai/Plansetiniai_(Tablet)/CatalogStore.aspx?CatID=PL_626"));
var codesNodes = page.DocumentNode.SelectNodes("//td[#class='mainContent']//div[#class='itemNormal']//div[#class='itemCode']");
var pricesNodes = page.DocumentNode.SelectNodes("//td[#class='mainContent']//div[#class='itemNormal']//div[#class='itemCode']//parent::div//div[#class='itemBoxPrice']");
if (codesNodes == null || pricesNodes == null)
return new List<CodeAndPrice>();
var codes = codesNodes.Select(node => node.InnerText.Replace("kodas", "").Replace(" ", "").Replace(": ", ""));
var prices = pricesNodes.Select(node => node.InnerText.Replace(" ", "").Replace(" €", ""));
return codes.Zip(prices, (code,price)=> new CodeAndPrice() { Code = code, Price = price }).ToList();
}
private async void Form1_Load(object sender, EventArgs e)
{
var results = await DataScraping();
foreach (var rez in results) {
table.Rows.Add(rez.Code, rez.Price);
}
}
}
Passing __doPostBack('designer1$ctl11$ctl00$MainCatalogSquare1$XDataPaging1','paging.1'); into the browser's console, page 2 is loaded, by changing "paging.*", browser loads page *+1
What is the simplest way to manipulate javascript, that I will be able to change page while scraping data and scrape data from other pages of this website?
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; }
}
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.
I'm using div instead of iframe to call a page but as soon as the other page loads in div then after clicking on any button, or selecting radiobutton, these events give this error
This is how I load div
<script type="text/javascript">
$(function () {
setInterval(function () {
$('#result').load('frmChatRequest.aspx', function () {
});
}, 10000);
});
</script>
This is frmChatRequest.aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt_chatRequest = LookupChat.getPendingRequestInMyChat("",Int64.Parse(_objSession.LoginID), _objSession, _errMsg);
ClsDataBind.DoGridViewBind(gdvChatRequestRoom, dt_chatRequest, _errMsg);
myMarqueeChatRequest.InnerText = "You Have " + dt_chatRequest.Rows.Count.ToString() + " new chat request/s in your rooms in last 15 minutes";
}
}
protected void gdvChatRequestRoom_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
HiddenField hdn = ((HiddenField)gdvChatRequestRoom.Rows[0].Cells[0].FindControl("hdnAddPeople"));
string strHdnValue = hdn.Value;
//Button btn = ((Button)gdvChatRequestRoom.Rows[0].Cells[3].FindControl("btnAccept"));
//string strBtnID = btn.ID;
string strBtnID = e.CommandArgument.ToString();
string query = "select * from Q116 where Q116002="+strBtnID+ " and Q116001="+ hdn.Value ;
_objQ116.SelectAll(query);
_objQ116.Q116DF2 = _objSession.LoginID;
_objQ116.Update(_objQ116.Q116DF2);
_objQ116.SelectAll(query);
_objQ116.Q116004 = DateTime.Now.ToString("hh:mm:ss");
_objQ116.Update(_objQ116.Q116004);
//insert in Q119
// _objQ116.Update(Q116004);
//_objLOG2.SelectAll(query);
//DateTime dt1 = DateTime.UtcNow.AddHours(5.5);
//string str = dt1.ToString();
//_objLOG2.Update(str);
//Write code to add to card
}
if (e.CommandName == "Reject")
{
HiddenField hdn = ((HiddenField)gdvChatRequestRoom.Rows[0].Cells[0].FindControl("hdnAddPeople"));
string strHdnValue = hdn.Value;
//Button btn = ((Button)gdvChatRequestRoom.Rows[0].Cells[3].FindControl("btnAccept"));
//string strBtnID = btn.ID;
string strBtnID = e.CommandArgument.ToString();
string query = "delete from Q116 where Q116001=" + hdn.Value + " and Q116002=" + "'" + strBtnID + "'";
// _objQ116.SelectAll(query);
Educity.EduDB.Select(query);
//Write code to add to card
}
Response.Redirect(Request.Url.AbsolutePath);
}
The ASP.NET webforms JavaScript and markup is probably messing up the hosting page and this is why a whole page is normally loaded in an iframe.
Have you considered using custom controls? They are really easy and encapsulate functionality into objects that can be included in any web page. It looks like frmChatRequest would be better as a control. Building a custom control is very similar to building a aspx webforms page, but it can then be re-used.
For more info on custom controls see http://msdn.microsoft.com/en-us/library/zt27tfhy.ASPX