简体   繁体   English

在View(ASP.NET MVC)中获取特定的dataTable单元格值

[英]Get specific dataTable cell values in View (ASP.NET MVC)

I am trying to find a way to access specific cells in a DataTable in View. 我试图找到一种方法来访问视图中的数据表中的特定单元格。 The DataTable was created in controller. DataTable是在控制器中创建的。 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: 和partialView代码:

<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? 如何在视图中遍历DataTable单元并获取特定单元?

I really don't understand why do you need to use a DataTable . 我真的不明白为什么您需要使用DataTable You can always create a class with structure you need. 您始终可以创建具有所需结构的类。 It will be much easier to us simple POCO's in your views. 在您看来,对我们来说简单的POCO将更加容易。

You haven't provided your XML so I made some examples for very simple version: 您尚未提供XML,所以我为非常简单的版本提供了一些示例:

<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 : 对于此类XML,您可以创建一个表示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: 然后,您可以使用读取XML的方法,例如:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM