I tries to fill webgrid using one answered
question and an article, But I can not my all rows repeat same as value. All rows values are the same as others. I have been debugging to solve this strange problem. But I can not:
public class MyViewModel
{
public IEnumerable<string> Columns { get; set; }
public IEnumerable<dynamic> Values { get; set; }
public bool HasNext { get; set; }
public bool HasPrevious { get; set; }
}
public class JobController : Controller
{
public ActionResult Index(int? page)
{
ViewData["Customers"] = new SelectList(CustomerOperation.GetCustomers().Items, "Id", "Name", null);
ViewData["Jobs"] = new SelectList(JobOperation.GetCustomersAssemblyList().Items, "scheduleId", "name", null);
const int pageSize = 10;
ViewBag.CurrentPage = (page ?? 0);
if (Session["CustomerId"]!=null && Session["ScheduleId"]!=null)
{
int customerId = ConvertUtil.ToInt(Session["CustomerId"]);
int scheduleId = ConvertUtil.ToInt(Session["ScheduleId"]);
var model = GetPagedVals((page ?? 0) * pageSize, pageSize, customerId, scheduleId);
ViewBag.HasPrevious = model.HasPrevious;
ViewBag.HasMore = model.HasNext;
return View(model);
}
else
return View();
}
public MyViewModel GetPagedVals(int skip, int take, int Id, int scheduleId)
{
Session["CustomerId"] = Id;
Session["ScheduleId"] = scheduleId;
DataTable dt = JobOperation.GetJobsBySchedulerIdAndCustomerId(scheduleId, Id);
List<dynamic> dataList = new List<dynamic>();
dynamic expando = new ExpandoObject();
var p = expando as IDictionary<String, object>;
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName);
foreach (DataRow dr in dt.Rows)
{
foreach (string columnName in columnNames)
{
p[columnName] = ConvertUtil.ToString(dr[columnName]);
}
dataList.Add(expando);
}
var result = dataList.Skip(skip).Take(take).ToList();
var model = new MyViewModel();
model.Columns = columnNames;
model.Values = result;
model.HasNext = (skip + 10 < dataList.Count);
model.HasPrevious = (skip > 0);
ViewBag.HasPrevious = model.HasPrevious;
ViewBag.HasMore = model.HasNext;
return model;
}
Result is below:

But All row is the same as anthers! Result must be below :

My sql queries working good. No problem sql. My repeated rows last row. How to solve this strange problem.
You only ever create one
ExpandoObjectinstance.You add this same instance to the list once for each row, overwriting the properties each time.
You need to create a
newinstance for each row.