:::warning
SQL server
:::
```
// 新增資料庫
CREATE DATABASE `db`
// 新增欄位
ALTER TABLE dbo.Btns
ADD Btn_test VARCHAR(100) NULL,
Btn_test2 INT NULL ;
// 新增資料
INSERT INTO Btns (menu_id,Btn_url,Btn_name,Btn_type,Btn_seq) VALUES
('??','/pd_cost/create','新增','create',1)
,('??','/pd_cost/edit','編輯','edit',2)
,('??','/pd_cost/delete','刪除','delete',3)
```
:::success
View
:::
```
//Razor語法
@Html.TextBox(Id/name, value)
@Html.CheckBox(text, true/false, new { class="" })
@Html.Hidden(name/id, value)
@Html.RadioButton(name/id, value, true/false)
@Html.RadioButtonFor(model => model.column, new { id = "id1", Name = "column" })
@Html.Label("id1", "text")
// db.column 用varchar 可以通用
@Html. TextArea (name,Value)
// 取得當下model資料
const data = @Html.Raw(Json.Encode(Model));
console.log(data);
$.ajax({
url: 'GetStoreList',
type: 'GET',
success: function (item) {
console.log(item)
item.forEach(i => {
if (i.storehouse_id == data) {
return i.storehouse_factory
}
})
},
error: function (error) {
console.log("Error: ", error);
}
});
```
:::warning
Controller
:::
```
//判斷資料安全性(解除)
namespace 內一層
[ValidateInput(false)]
//輸出的三種寫法
Console.Write(i + " ")
Console.WriteLine("{0} Score: {1}", student.Last, student.score)
Console.WriteLine($"{student.Last} 123")
public ActionResult Testdb() function名第一個字要大寫
{
using (Model1 db = new Model1())
{
var actType = db.hr_insure_claim
.Select(s => s.insclm_name)
.Distinct() //抓出不重複的語法
.ToList();
return Json(actType, JsonRequestBehavior.AllowGet);
}
}
public ActionResult Gettype(string term)
{
using (Model1 db = new Model1())
{
// 使用 Contains 改為 Equals 以精確匹配選項值
var type = db.hr_business_trip_setting
.Where(s => s.tripset_name == term)
.Select(s => new { label = s.tripset_type }) //設定新名稱
.FirstOrDefault(); //第一個相同的項目
return Json(type, JsonRequestBehavior.AllowGet);
}
}
//判斷兩個欄位
var data = (from item in db.acct_bankacct
join reaitem in db.as_account_reason
on item.bankacct_code equals reaitem.arName
select item.bankacct_alias).ToList();
public JsonResult GetStoreList()
{
var storeList = db.wm_storehouse
.Select(s => new { s.storehouse_id, s.storehouse_name ,s.storehouse_factory })
.ToList();
return Json(storeList, JsonRequestBehavior.AllowGet);
}
```
### 匯出PDF
```
Install-Package iTextSharp -Version 5.5.13.3 --PDF套件--
Install-Package itextsharp.xmlworker --解析html--
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
-- view --
let index = 1;
while (newcontent.includes('%SIGN%')) {
newcontent = newcontent.replace('%SIGN%', `
<span id="previewImagebox${index}" style="width:100px;height:50px">
<button type="button" class="btn btn-outline-primary btn-sm mx-2" data-toggle="modal" data-target="#signatureModal" style="display:inline-block" onclick="setPreviewImageId(${index})">
簽名
</button>
</span>
`);
index++;
}
let previewImageId;
function setPreviewImageId(index) {
previewImageId = index;
}
const checkarry = {}
// 簽名保存
function saveSignature() {
// 獲取Canvas元素
var canvas = document.getElementById("Po_filename");
// 將Canvas的內容轉換為DataURL
var base64Data = canvas.toDataURL("image/jpg");
// 創建一個Image元素
var img = new Image();
img.src = base64Data;
// 獲取預覽圖像的img元素
$(`#previewImagebox${previewImageId}`).html(`
<span style="background-image:url(${base64Data});width:100px;height:50px;background-size:100%;display: inline-block;background-repeat: no-repeat;background-position: center;"></span>
<span class="changeimgdata${previewImageId}"></span>
`)
checkarry[previewImageId] = base64Data;
undoStack = [];
context.clearRect(0, 0, canvas.width, canvas.height);
}
$('#imgdata').val(JSON.stringify(Object.values(checkarry)));
-- controller --
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Agree_Book_Sign agree_Book_Sign, string imgdata)
{
try
{
// 解析 JSON 数组
string[] imgDataArray = JsonConvert.DeserializeObject<string[]>(imgdata);
db.Agree_Book_Sign.Add(agree_Book_Sign);
db.SaveChanges();
// 指定保存 PDF 的路徑
string PDFPath = Server.MapPath("~/Uploads/Agree_Book_Sign");
if (!Directory.Exists(PDFPath))
{
Directory.CreateDirectory(PDFPath);
}
string pdfPath = Path.Combine(PDFPath, agree_Book_Sign.AGBsign_booktitle+".pdf");
// 保存图片到服务器
string imgPath = Server.MapPath("~/Uploads/Agree_Book_Sign/img");
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
SaveImages(imgDataArray, imgPath);
// 生成 PDF 並保存到指定路徑
GeneratePdf(agree_Book_Sign, pdfPath, imgPath, imgDataArray.Length);
}
catch (Exception ex)
{
// 記錄例外(可選)
System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
return View("Error", new HandleErrorInfo(ex, "Agree_Book_Sign", "Create"));
}
return RedirectToAction("Index"); // 成功後重定向到其他頁面
}
private void SaveImages(string[] imgDataArray, string imgPath)
{
for (int i = 0; i < imgDataArray.Length; i++)
{
var base64Data = imgDataArray[i].Replace("data:image/png;base64,", "");
byte[] imageBytes = Convert.FromBase64String(base64Data);
string filePath = Path.Combine(imgPath, $"image{i}.png");
System.IO.File.WriteAllBytes(filePath, imageBytes);
}
}
private void GeneratePdf(Agree_Book_Sign model, string pdfPath, string imgPath, int imgCount)
{
string chineseFontPath = Server.MapPath("~/Assets/font/kaiu.ttf");
using (FileStream stream = new FileStream(pdfPath, FileMode.Create))
{
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
// 設定中文字型
BaseFont chineseBaseFont = BaseFont.CreateFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font chineseFont = new Font(chineseBaseFont, 12, Font.NORMAL);
//// 構建 HTML 字符串
string htmlContent = $@"
<body style='font-family: KaiTi, 微軟正黑體, Arial, sans-serif;'>
{model.AGBsign_file}
</body>";
string imgpath = Server.MapPath("~/Uploads/Agree_Book_Sign/img");
for (int i = 0; i < imgCount; i++)
{
string placeholder = $"<span class=\"changeimgdata{i + 1}\"></span>";
string imageTag = $"<img src=\"{Path.Combine(imgPath, $"image{i}.png")}\" style=\"width:100px;height:50px;\" />";
htmlContent = htmlContent.Replace(placeholder, imageTag);
}
model.AGBsign_file = htmlContent;
db.SaveChanges();
// 使用 XMLWorker 解析 HTML
using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlContent)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, null, System.Text.Encoding.UTF8, new CustomFontFactory());
}
document.Close();
}
}
// 自定義字體工廠(如需要自定義字體)
public class CustomFontFactory : XMLWorkerFontProvider
{
public override iTextSharp.text.Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color)
{
// 在此處自定義字體
return base.GetFont(fontname, encoding, embedded, size, style, color);
}
}
```
:::warning
### [資料庫同步語法](https://blog.talllkai.com/ASPNETCoreMVC/2023/04/18/DatabaseFirst#google_vignette)
:::