【问题标题】:unble to convert data table to list in c#无法将数据表转换为 C# 中的列表
【发布时间】:2020-02-07 12:26:10
【问题描述】:

我想将数据表数据显示为 html,以便我将数据表转换为列表。但得到 erorr 不能隐式地将类型 'System.web.mvc.viewresult' 转换为 system.collection.genericlist

 public ViewResult Report_trans_consumption(DateTime? fromDate, DateTime? toDate)
        {
            ViewBag.fromDate = fromDate;
            ViewBag.toDate = toDate;
            List<Trans_energycons_ReportModel> model = null;
            using ("constr"))
            { 
                con.Open();
                SqlCommand cmd_get_transformer_consumption = new SqlCommand(@"SELECT 
    Date,units
    FROM [Total_Power]) desc", con);
                SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
                DataTable dt = new DataTable();
                da_get_trans_consumption.Fill(dt);
                Trans_energycons_ReportModel m =new Trans_energycons_ReportModel();
                foreach (DataRow row in dt.Rows)
                {
                    string deviceDate = row["Date"].ToString();
                    string units = row["Units"].ToString();
                    m.DeviceDate =Convert.ToDateTime(deviceDate);
                    m.Units =Convert.ToDouble(units);
                    model.Add(m);//getting error here
                }
            }
            return View(model); 
        }
    }

型号

  public class Trans_energycons_ReportModel
    {
        public DateTime DeviceDate { get; set; }
        public double Units { get; set; }

    }

【问题讨论】:

    标签: c# generic-list


    【解决方案1】:

    下面一行不起作用

    model = dt.AsEnumerable().ToList();
    

    您必须从数据表中手动映射您的属性,例如

     foreach(DataRow row in dt.Rows)
     { 
         string deviceDate = row["DeviceDate"].ToString();
         string units = row["Units"].ToString();
         // convert your data and assign them in model and then use that model
     }
    

    编辑:

    您的返回类型是List&lt;Trans_energycons_ReportModel&gt;

    所以你应该返回return model; 而不是return View(model);

    【讨论】:

    • 感谢您的建议,但是返回 View(model);我也在这里出错。
    • 针对您的问题进行了编辑,请查看更新后的答案。
    • 将列表更改为ActionResult
    【解决方案2】:

    List&lt;Trans_energycons_ReportModel&gt; 更改为ViewResultActionResult,如以下代码:

    public ViewResult Report_trans_consumption(DateTime? fromDate, DateTime? toDate)
    {
     ....
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      相关资源
      最近更新 更多