本文介绍了如何修复outofrange异常/找不到列1.在MVC中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在MVC视图中调用xml数据来显示它但得到异常错误。任何帮助将不胜感激。



我尝试过:



-------- XML ----

I am trying to call the xml data in MVC view to display it but get the exception error. Any help will be much appreciated.

What I have tried:

--------XML----

<root>
    <states>
        <state>
            <statename>Abia</statename>
            <stateid>101</stateid>
        </state>
        <state>
            <statename>Adamawa</statename>
            <stateid>102</stateid>
        </state>
        <state>
            <statename>Akwa Ibom</statename>
            <stateid>103</stateid>
        </state>
        ...
    </states>
</root>





----- C#code ---



-----C# code---

public class XMLREADER
{
    public List<Products> ReturnListOfProducts()
    {
        string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/ProductData.xml");//Path of the xml script  
        DataSet ds = new DataSet();//Using dataset to read xml file  
        ds.ReadXml(xmlData);

        var products = new List<Products>();
        products = (from rows in ds.Tables[0].AsEnumerable()
                    select new Products
                    {
                        StateName = rows[0].ToString(),
                        StateId = Convert.ToInt32(rows[1].ToString()),
                    }).ToList();

        return products;
    }
}

推荐答案

public List<Products> ReturnListOfProducts()
{
    string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/ProductData.xml");
    DataSet ds = new DataSet();
    ds.ReadXml(xmlData);

    return (from rows in ds.Tables[1].AsEnumerable()
            select new Products
            {
                StateName = rows[0].ToString(),
                StateId = Convert.ToInt32(rows[1]),
            }).ToList();
}



您可以通过使用调试器更快地找到它。


You could have found this out for yourself much faster by using the debugger.


这篇关于如何修复outofrange异常/找不到列1.在MVC中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:34