分享人:徐晉
1.表單提交涉及到多個表的改變時,使用CommitSql。
當一個表單提交時,涉及到兩個及兩個以上表的增刪改查時,使用CommitSql語句.例如:一個表單提交,會向兩個表格填加數據時。
A.Add(loginUser);
B.Add(loginUser);
這樣寫會出問題,若A添加成功,而B添加失敗,數據庫會把A存入,而B沒有存入,但這并不是我們想要的結果。我們想要的正常結果是若B失敗,A也不應存入數據庫。
這時,我們可以改為以CommitSql的形式提交:
tmpSql = A.ReturnSql(loginUser);
tmpSql += B.ReturnSql(loginUser);
public static void CommitSql(string sqlString, int affectNum)
{
OperatorTable<T, Q> tmpDbObject = Activator.CreateInstance<Q>();
if (sqlString.Replace(';', ' ').Trim() == "")
{
if (affectNum == 0)
return;
else
throw new Common.DB.DBException(string.Format("數據庫操作不符合預期, 預期: {0}, 實際: {1}",
affectNum, 0));
}
sqlString = SqlBuilderFactory.GetSqlBuilder(tmpDbObject).GetCommitSql(sqlString);
SqlRunner.commitSql(sqlString, affectNum, tmpDbObject);
}
DB.A.CommitSql(tmpSql, 0);
//后面的0的含義是你提交的數據里改變的字段的數量,如果不確定,就寫0
總結:Add方法相當于我們每次只是操作一個數據,CommitSql相當于我們把所有需要增刪查改的數據打包一起提交到數據庫。
2. 前臺動態生成表單時若涉及上傳文件遇到的問題及解決方法。
前臺拼接語句時使用框架中的<uc1:FileUpload runat="server" id="FileUpload" />
,我這里使用的是<input name=’file’ type=’file’>
。但是這樣寫的話,只能獲取到文件的名字,無法真正上傳文件,需要在后臺寫一個上傳文件的方法。
uc1:FileUpload
中上傳文件的方法寫在FileUploadHandler.aspx.cs
文件中,模仿這個文件中的方法在后臺寫了一個上傳文件的方法。實際操作的時候大家可以對照原文件去改。
private string UploadFile(int index)
{
HttpPostedFile curFile = this.Request.Files[index];
curFile.InputStream.Seek(0, SeekOrigin.Begin);
byte[] b = new byte[curFile.InputStream.Length];
curFile.InputStream.Read(b, 0, b.Length);
Random ran = new Random();
string orgName = curFile.FileName;
string imgindex;
string fileName;
string filePath;
string relativePath = "Upload\\File\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
if (!Directory.Exists(Server.MapPath("/") + relativePath))
Directory.CreateDirectory(Server.MapPath("/") + relativePath);
int i = 0;
do
{
if (i++ > 10)
throw new Common.WebException.WebException("生成地址重復次數太多");
imgindex = DateTime.Now.ToString("yyyyMMddHHmmssttt") + ran.Next(100, 999).ToString();
fileName = Common.Encryptor.Get16MD5Str(imgindex) + Common.Config.ServerId + System.IO.Path.GetExtension(curFile.FileName);
filePath = Server.MapPath("/") + relativePath + fileName;
} while (System.IO.File.Exists(filePath));
System.IO.File.WriteAllBytes(filePath, b);
Response.StatusCode = 200;
Response.Write("/" + (relativePath + fileName).Replace("\\", "/"));
return "/" + (relativePath + fileName).Replace("\\", "/");
}
3. 前臺接收后臺json時遇到的問題及解決方法。
if(‘<%=Request[‘action’]%>’ == ‘edit’){
var jsonData = <%=jsonPositions%>;
…….
}
若為edit操作沒有問題,但是若不是edit操作,頁面加載會出現問題。因為頁面加載時即使執行不到這句var jsonData = <%=jsonPositions%>
,也會把<%%>
中的語句執行一遍。因為不是edit操作,后臺中的jsonPositions
是沒有值的,那么這句話就變成了var jsonData = ;
這就會到導致頁面加載出現錯誤。于是,改成:
var jsonStr = '<%=jsonPositions %>';
var jsonData = JSON.parse(jsonStr);
有時候,json串中會包含一些非法字符,那么在執行JSON.parse(jsonStr)
時也會出現錯誤,導致頁面加載出現問題,例如“\”等,可以改成以下方式解決該問題。
var jsonStr = '<%=jsonPositions %>';
var jsonTmp = jsonStr.replace(/\\/g, '!');
var jsonData = JSON.parse(jsonTmp);