asp.net前台多条数据存入数据库?
ASP.NET WEB前台的表格
例如 行 物料号 数量 单价 金额 库位
可以动态的进行编辑、增加行或删除行,编辑完毕后,点击按钮一次性存入数据库,类似进销存的单据。
想问的是,
1.前台用的是服务器的控件或table还是其他?
2.一次性提交的时候,是采用循环的方式转化成实体类?如果是如何转?然后通过SQLHelp类存入数据的吗?还是其他方式?
最好有个实例,不够分另开贴给。
asp.net
[解决办法]
1.前台用的是服务器的控件或table还是其他?
服务器控件你用哪个?只是保存临时数据,并且显示在当前用户页面
我觉得最好用list保存多条数据在服务器(不是保存在数据里),可以用ViewState或Session,每新增一条数据,就加到list.Add(),因为是临时数据,不提供编辑,只要新增和保存.
2.一次性提交的时候,是采用循环的方式转化成实体类?如果是如何转?然后通过SQLHelp类存入数据的吗?还是其他方式?
前台肯定是一次性提交一个list,后台用list生成多条insert语句,通过循环连接在一起,一次性提交给数据库
[解决办法]
参考:
//前台通过ViewState保存数据在服务器上
public List<TeacherWorkingTime> AddTeacherWorkingTimeList
{
get
{
if (ViewState["AddTeacherWorkingTimeList"] == null)
{
ViewState["AddTeacherWorkingTimeList"] = new List<TeacherWorkingTime>();
}
return ViewState["AddTeacherWorkingTimeList"] as List<TeacherWorkingTime>;
}
set
{
ViewState["AddTeacherWorkingTimeList"] = value;
}
}
//新增临时数据,并且到list
protected void btn_AddItem_Click(object sender, EventArgs e)
{
int weekday = int.Parse(this.ddl_Weekday.SelectedValue);
string StartTime = this.ddl_StartTime.SelectedValue.Replace(":", "");
string EndTime = this.ddl_EndTime.SelectedValue.Replace(":", "");
int intStartTime = int.Parse(StartTime);
int intEndTime = int.Parse(EndTime);
TeacherWorkingTime model = new TeacherWorkingTime();
model.TeacherID = HttpContextUtility.GetCurrentDataItemID();
model.Weekday = weekday;
model.StartTime = StartTime;
model.EndTime = EndTime;
model.Remarks = this.txt_Remarks.Text;
this.AddTeacherWorkingTimeList.Add(model);
}
//前台保存
protected void btn_Save_Click(object sender, EventArgs e)
{
List<TeacherWorkingTime> dataModelList = new List<TeacherWorkingTime>();
int TeacherID = HttpContextUtility.GetCurrentDataItemID();
foreach (var item in AddTeacherWorkingTimeList)
{
TeacherWorkingTime model = new TeacherWorkingTime();
model.TeacherID = TeacherID;
model.Weekday = item.Weekday;
model.StartTime = item.StartTime.Replace(":", "");
model.EndTime = item.EndTime.Replace(":", "");
model.Remarks = item.Remarks;
dataModelList.Add(model);
}
ExecuteResult result = TeacherSRV.UpdateModel_Weekday(dataModelList, TeacherID);
if (result.ActionStatus == ActionStatusType.Success)
{
Response.Redirect(BOSUtility.ConstructFromEditPageToViewPageURL(1));
}
}
//后台一次性提交的代码
public static ExecuteResult UpdateModel_Weekday(List<TeacherWorkingTime> list, int TeacherID)
{
StringBuilder sb = new StringBuilder();
sb.Append("DELETE TeacherWorkingTime WHERE TeacherID=@TeacherID; "+Environment.NewLine);
foreach (var item in list)
{
sb.Append("INSERT INTO TeacherWorkingTime(TeacherID,Weekday,StartTime,EndTime,Remarks) ");
sb.Append("VALUES(@TeacherID," + item.Weekday + ",'" + item.StartTime + "','" + item.EndTime + "','" + item.Remarks + "'); ");
sb.Append(Environment.NewLine);
}
SqlCommand command = new SqlCommand();
command.CommandText = sb.ToString();
command.Parameters.Add("@TeacherID", SqlDbType.Int).Value = TeacherID;
return DBProvider.DefaultDBOperator.ExecuteNonQuery(command);
}