如何解决expando奇怪的行为来填充mvc3 webgrid?

时间:2012-07-04 12:59:28

标签: c# asp.net-mvc asp.net-mvc-3 model-view-controller

我尝试使用一个answered questionan article填充webgrid,但我的所有行都不能重复与值相同。所有行值都与其他行相同。我一直在调试解决这个奇怪的问题。但我不能:

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;
   }

结果如下:

enter image description here

但是所有的行与花药相同!结果必须如下: enter image description here 我的SQL查询运行良好。没问题sql。我的重复排在最后一排。如何解决这个奇怪的问题。

1 个答案:

答案 0 :(得分:1)

dynamic expando = new ExpandoObject();

您只需创建一个 ExpandoObject个实例 您可以为每行向列表添加一次相同的实例,每次都覆盖属性。

您需要为每一行创建一个new实例。