How to get html table values in code behind c# - c#

I have one HTML table. In the table I added a tr during run-time using the javascript code below -
var table = document.getElementById("myTable");
var tab_length= table.rows.length;
var row = table.insertRow(tab_length);
row.id="Row"+tab_length;
var Ord_ID = row.insertCell(0);
var Ord_Name = row.insertCell(1);
var Ord_Qty = row.insertCell(2);
var Ord_Price = row.insertCell(3);
var Ord_Total = row.insertCell(4);
var Del_Button = row.insertCell(5);
var Edit_Button = row.insertCell(6);
Ord_ID.innerHTML = document.getElementById("Ord_ID").value;
Ord_Name.innerHTML = document.getElementById("Ord_Name").value;
Ord_Qty.innerHTML = document.getElementById("Ord_Qty").value;
Ord_Price.innerHTML = document.getElementById("Ord_Price").value;
But I can not access the tr values in c#. Can anyone please help with this problem?

I would use JQuery to send an Ajax POST request. If you want to do error handling, you can return either a success or error message in JSON format. Have a look at this link for more information:
http://api.jquery.com/jquery.ajax/

Related

WebScraper C# + htmlagilitypack

i started develop application. Me need take some informations from website after download it in database, and after I need treatment this informations.
Well, I don't have enough experience and be grateful any of your recomendation.
for example - I'll work with sport site. (https://terrikon.com/football/spain/championship/)
I need receive informations from table and download this data in DB.
I tried some ways download data and understand that best way - use "htmlagilitypack".
I read documentation about work with this library and best that i did:
using System;
using System.Xml;
using HtmlAgilityPack;
namespace Parser
{
class Program
{
static void Main(string[] args)
{
var html = #"https://terrikon.com/football/spain/championship/";
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(html);
var node = htmlDoc.DocumentNode.SelectSingleNode("//head/title");
var table = htmlDoc.QuerySelector("#champs-table > table");
var tableRows = table.QuerySelectorAll("tr");
foreach (var row in tableRows)
{
var team = row.QuerySelector(".team");
var win = row.QuerySelector(".win");
var draw = row.QuerySelector(".draw");
var lose = row.QuerySelector(".lose");
Console.WriteLine(team.OuterHtml );
};
}
}
}
I can receive title of website or all informations, if I'll change this string
var node = htmlDoc.DocumentNode.SelectSingleNode("//head");
Could you give me advice how can I get informations only from table?
thanks for tour attention
I would recommend to also install a Css selector extension for HtmlAgilityPack which can be found here:
https://github.com/hcesar/HtmlAgilityPack.CssSelector
With that you can Query your nodes with css selectors.
To get the information from that table you will have to know the CSS selector for it.
In this case its:
#champs-table > table
So to get whole table you could do it like this:
var table = htmlDoc.QuerySelector("#champs-table > table");
// then query rows of that table:
var tableRows = table.QuerySelectorAll("tr");
// Now each element it tableRows is a <tr> from that html table
// you could access every value in a for each loop
foreach(var row in tableRows)
{
var team = row.QuerySelector(".team"); // "team" is a css class applied to <td> containing the team name
var win = row.QuerySelector(".win");
var draw = row.QuerySelector(".draw");
var lose = row.QuerySelector(".lose");
}

What is the best way to deserialize Azure Search result to your own model?

Currently what I'm doing is serializing the JsonResult.Data then Deserialized into dynamic variable before looping in each row and get the Document. Is there any way to handle this? Thanks
if (string.IsNullOrWhiteSpace(searchTerm_))
searchTerm_ = "*";
_azureSearch = new AzureSearchService("afindexdev");
JsonResult result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = _azureSearch.SearchAssetFactory(searchTerm_).Results
};
string json = JsonConvert.SerializeObject(result.Data);
var resultJsonString = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
foreach (dynamic row in resultJsonString)
{
var associatemItem = new AssociatedItem();
associatemItem.Id = row.Document.Id;
associatemItem.Title = row.Document.Title;
associatemItem.Type = row.Document.Type;
searcResult.AssociatedItems.Add(associatemItem);
}
What about this?
var associatedItem = Newtonsoft.Json.JsonConvert.DeserializeObject< List < AssociatedItem > >(json);
That way you don't have to make your object yourself.
You can define your model with properties which you want to deserialize with attribute [SerializePropertyNamesAsCamelCase]. This attribute is included to Microsoft.Azure.Search library. After that, all you need to do is to define your model in search generic - like this Hotel class
var sp = new SearchParameters();
if (!String.IsNullOrEmpty(filter))
{
sp.Filter = filter;
}
DocumentSearchResult<Hotel> response = indexClient.Documents.Search<Hotel>(searchText, sp);
You can find more info here

How to convert Json in C#?

I am using c#.net with ASP.Net MVC.
I have following code
var lstrelations = _people.GetAllUsers();
List<string> lstEmailAddresses = lstrelations.Select(p =>p.EmailID).ToList<string>();
return Json(lstEmailAddresses, JsonRequestBehavior.AllowGet);
This is generating output like
["xxy#xct.com", "text13#tds.com", "sdxxa#xys.com"]
but I want generate Json like
["EmailID:xxy#xct.com", "EmailID:text13#tds.com", "EmailID:sdxxa#xys.com"]
I want to put name of each address like "EmailID"
try with this code...
var lstrelations = _people.GetAllUsers();
var lstEmailAddresses = lstrelations.Select(p => new { EmailID = p.EmailID }).ToList();
Json(lstEmailAddresses, JsonRequestBehavior.AllowGet);

Having trouble with a very basic search -- no results

I have Elasticsearch up and running. Using Sense within Marvel, I am able to get a result, with this query:
GET _search
{
"query": {
"query_string": {
"query": "massa"
}
}
}
My c# code, trying to recreate the above:
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node).SetDefaultIndex("mediaitems");
var client = new ElasticClient(settings);
var results = client.Search<stuff>(s => s
.Query(qs => qs.QueryString(q => q.Query("massa"))));
var d = results.Documents;
But unfortunately I'm not getting any results, nothing in "results.Documents". Any suggestions? Maybe a way to see the generated json? What is the simplest way to just query everything in an index? Thanks!
Even though your search results are going to be mapped to the proper type because you are using .Search<stuff>, you still need to set the default type as part of your query.
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node).SetDefaultIndex("mediaitems");
var client = new ElasticClient(settings);
var results = client.Search<stuff>(s => s
.Type("stuff") //or .Type(typeof(stuff)) if you have decorated your stuff class correctly.
.Query(qs => qs.QueryString(q => q.Query("massa"))));
var d = results.Documents;
Additionally, your results response contains a ConnectionStatus property. You can interrogate this property to see the Request and Response to/from Elasticsearch to see if your query is being executed as you expect.
Update: You can also set a default type the index settings as well.
var settings = new ConnectionSettings(node).SetDefualtIndex("mediaitems");
settings.MapDefaultTypeIndices(d=>d.Add(typeof(stuff), "mediaitems");
You can also check nest raw client
var results = client.Raw.SearchPost("mediaitems", "stuff", new
{
query = new
{
query_string = new
{
query = "massa"
}
}
});
You can get the values of search request URL and JSON request body as under:
var requestURL = response.RequestInformation.RequestUrl;
var jsonBody = Encoding.UTF8.GetString(response.RequestInformation.Request);
You can find other useful properties in RequestInformation for debugging.

Convert GridView to List<object>

Hi and thanks in advance. I'm having a problem implementing a suggestion that I found here: Convert contents of DataGridView to List in C#
I am grabbing a GridView from a Master page and I need to add a row to the table then rebind it. I am accessing the GridView via a public property on the Master page which is being returned with data. So basically I have done this:
var gsr = master.GridSearchResults;
gsr (gsr != null)
{
var so = new List<MyProperties>();
so = gsr .Rows.OfType<DataGridViewRow>().Select(r => r.Cells.OfType<DataGridViewCell>().Select(c => c.Value).ToArray()).ToList<MyProperties>();
so.Add(new MyProperties()
{
Id = id,
Date = date,
Building = buildingName,
Street = streetName
}
gsr.DataSource = so;
gsr.DataBind();
}
But I'm receiving an error that it cannot convert an instance argument type System.Collections.Generic.IEnumerable<'object[]'> to System.Collections.Generic.IEnumerable<'MyProperties'>. I thought the problem was the call to the array but if I remove it then I just get a variation of the same error.
Turns out my issue was that I shouldn't have been getting the gridview in the first place but getting the the Gridview's source which was in session. So I solved it like this:
var master = (Tab)Master;
master.GridSearchResults.DataSource = null;
var sessions = new Sessions();
sessions.SlideOutSource.Add(new MyProperties {
Id = Id,
StartDate = hidStartDate.Value,
Installation = txtInstall.Text,
Command = txtCommand.Text });
master.GridSearchResults.DataSource = sessions.SlideOutSource;
master.GridSearchResults.DataBind();

Categories

Resources