List.Add()问题:它只保存最后添加的项目,它重复绑定最后一个数据,请有人帮我清除它。我在mvc 4中尝试作为Begineer。我也在努力学习mvc 4的基本知识。感谢你提前。
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=@batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new MyCourseData();
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
答案 0 :(得分:5)
这是因为您在列表中添加了相同的MyCourseData实例,并且每次迭代都会更改值。 您需要为每次迭代创建MyCourseData的新实例,
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=@batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
var model = new MyCourseData();
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
}