public ActionResult AddBook(Models.AddBookArg arg) //回傳Json到前端在導向其他頁面 { Models.BookMangementService bookMangement = new Models.BookMangementService(); { if (ModelState.IsValid) { string BookID = bookMangement.InsertBookData(arg).ToString(); //**BookID用來作為導向明細頁面的索引值 return(RedirectToAction("Detail", new { BookID })); } } return(View(arg)); }
/// <summary> /// 新增書籍 /// </summary> /// <param name="arg">asss</param> /// <returns></returns> public int InsertBookData(Models.AddBookArg arg) { int BookID = -1; try //**如果日期是空值的話雖然可以存入資料庫 { //**但是在查詢的時候會沒辦法從DB(NULL)轉換成字串, DateTime date = DateTime.Parse(arg.BookBoughtDate); //**所以還是要 1.判斷日期不可以是空值 或是 2.當日期是空值的時候以空白字串存入資料庫 string cmdstr = @"INSERT INTO BOOK_DATA ([BOOK_NAME],[BOOK_CLASS_ID],[BOOK_AUTHOR],[BOOK_BOUGHT_DATE] ,[BOOK_PUBLISHER],[BOOK_NOTE],[BOOK_STATUS],[BOOK_KEEPER] ,[BOOK_AMOUNT],[CREATE_DATE],[CREATE_USER],[MODIFY_DATE] ,[MODIFY_USER]) VALUES( @BookName,@BookClassId,@BookAuthor,@BookBoughtDate ,@BookPublisher,@BookNote,@BookStatus,@BookKeeper ,@BookAmount,@CreateDate,@CreateUser,@ModifyDate ,@ModifyUser) SELECT SCOPE_IDENTITY()"; using (SqlConnection conn = new SqlConnection(this.GetDBConnectionString())) { conn.Open(); DateTime SysTime = DateTime.Now; SqlCommand cmd = new SqlCommand(cmdstr, conn); cmd.Parameters.Add(new SqlParameter("@BookName", arg.BookName)); cmd.Parameters.Add(new SqlParameter("@BookClassId", arg.BookClass)); cmd.Parameters.Add(new SqlParameter("@BookAuthor", arg.BookAuthor == null ? (Object)DBNull.Value : arg.BookAuthor)); cmd.Parameters.Add(new SqlParameter("@BookBoughtDate", arg.BookBoughtDate == null ? (Object)DBNull.Value : arg.BookBoughtDate)); cmd.Parameters.Add(new SqlParameter("@BookPublisher", arg.BookPublisher == null ? (Object)DBNull.Value : arg.BookPublisher)); cmd.Parameters.Add(new SqlParameter("@BookNote", arg.BookNote == null ? (Object)DBNull.Value : arg.BookNote)); cmd.Parameters.Add(new SqlParameter("@BookStatus", 'A')); //書籍狀態是'可借出' cmd.Parameters.Add(new SqlParameter("@BookKeeper", (Object)DBNull.Value)); cmd.Parameters.Add(new SqlParameter("@BookAmount", (Object)DBNull.Value)); cmd.Parameters.Add(new SqlParameter("@CreateDate", SysTime)); cmd.Parameters.Add(new SqlParameter("@CreateUser", "admin")); cmd.Parameters.Add(new SqlParameter("@ModifyDate", SysTime)); cmd.Parameters.Add(new SqlParameter("@ModifyUser", "admin")); SqlTransaction Tran = conn.BeginTransaction(); cmd.Transaction = Tran; try { BookID = Convert.ToInt32(cmd.ExecuteScalar()); //**BookID可以用來跳到編輯頁面 Tran.Commit(); } catch (Exception) { Tran.Rollback(); throw; } finally { conn.Close(); } //**如果書本簡介超過資料庫中設定的長度 會跳錯誤所以要注意長度限制 } } catch (Exception ex) { throw; } return(BookID); }