0

While i build the Project, It have a error like this:

Server Error in '/' Application.

The model item passed into the dictionary is of type 'System.Data.DataTable', but this dictionary requires a model item of type 'System.Collections.Generic.IList`1[TLayout.Models.DemoTable]'.

This is my Controller

public ActionResult Index()
        {
            var dm = new DemoTable();
            string connstring = "Server=localhost;Port=5432;User Id=postgres;Password=123456;Database=test";
            NpgsqlConnection conn = new NpgsqlConnection(connstring);
            conn.Open();
            string sql = "select * from demo";
            NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
            ds.Reset();
            da.Fill(ds);
            dt = ds.Tables[0];
            var demoid = dm.demoid.ToString();
            var demoname = dm.demoname;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                List<DataTable> dtb = new List<DataTable>();
                demoid = dt.Rows[i]["demoid"].ToString();
                demoname = dt.Rows[i]["demoname"].ToString();
                dtb.Add(dt);
            }
            return View(dt);
        }

This is my View, to show data to layout:

foreach (var item in Model)
{
    fields.Add(Html.X().ModelField().Mapping(@item.demoid.ToString()).Name("grid-alarm"));
    fields.Add(Html.X().ModelField().Mapping(@item.demoname.ToString()).Name("grid-check"));
}
Community
  • 1
  • 1
trungle.it
  • 97
  • 2
  • 8

1 Answers1

1
var list = dt.AsEnumerable()
             .Where(row => (int)row["demoid"] > 5)
             .Select(row => new
              {
                 demoid = Convert.ToInt32(row["demoid"]),
                 demoname = row["demoname"] != null ? 
                            row["demoname"].ToString() : 
                            String.Empty
              }).ToList();

Or you can define class:

public class myClass
{
  public int demoid;
  public string demoname;
}

and then:

List<myClass> list = dt.AsEnumerable()
             .Where(row => (int)row["demoid"] > 5)
             .Select(row => new myClass
             {
                 demoid = Convert.ToInt32(row["demoid"]),
                 demoname = row["demoname"] != null ? 
                            row["demoname"].ToString() : 
                            String.Empty
             }).ToList<myClass>();
Boris Gappov
  • 2,483
  • 18
  • 23