I am trying to find a way to access specific cells in a DataTable in View. The DataTable was created in controller. Code in conroller:
[ChildActionOnly]
public ActionResult _ls()
{
var getXMLlivescore = new HtmlDocument();
getXMLlivescore.Load("D://lscopy.xml");
DataTable matchTable = new DataTable();
matchTable.Columns.Add("put2forEventOr1", typeof(int));
matchTable.Columns.Add("country", typeof(string));
...
matchTable.Columns.Add("min", typeof(string));
matchTable.Columns.Add("extramin", typeof(string));
foreach (HtmlNode match in category.SelectNodes(".//match")){
//code to get xml tags
matchTable.Rows.Add(put2forEventOr1, country, ....., min, extramin);
}
return PartialView(matchTable);
}
and the partialView code:
<table>
@foreach (DataRow row in Model.Rows)
{
//get cell in row[0]
@if (row[0] == 3){
do some work
}
}
</table>
How can I iterate through DataTable cells in view and get specific cells?
I really don't understand why do you need to use a DataTable
. You can always create a class with structure you need. It will be much easier to us simple POCO's in your views.
You haven't provided your XML so I made some examples for very simple version:
<Elements>
<Element>
<Country>Peru</Country>
<Min>20</Min>
</Element>
<Element>
<Country>Armenia</Country>
<Min>9</Min>
</Element>
</Elements>
For such XML you can create a class that will represent an Element
:
public class Element
{
public string Country { get; set; }
public int Min { get; set; }
public string NotXmlProperty { get; set; }
}
And then you can use your method of reading XML or for example this one:
var xDoc = XDocument.Load(xmlFilePath);
IEnumerable<Element> elements = xDoc
.Descendants("Element")
.Select(x => new Element
{
Country = x.Element("Country").Value,
Min = Convert.ToInt32(x.Element("Min").Value),
NotXmlProperty = "Value"
});
After that accessing your data in the view should be very simple:
@model IEnumerable<Element>
<table>
@foreach(var element in Model)
{
<tr>
<td>@element.Country</td>
<td>@element.Min</td>
<td>@element.NotXmlProperty</td>
</tr>
}
<table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.