如何在ASP.NET MVC中動態生成和顯示條碼
ASP.NET MVC 是一個流行的 Web 開發框架,它允許開發人員建立強大且動態的 Web 應用程式。 Web 應用程式中的常見需求是能夠產生和顯示條碼影像。 條碼影像用於以機器可讀格式表示資料,並可由條碼掃描器讀取。
使用市場領先的C#庫IronBarcode,可以在ASP.NET MVC中動態生成和顯示條碼圖片。 該程式庫提供 API,使開發人員能夠輕鬆地跨平台生成各種格式的條碼圖像,例如 Code 39、Code 128 和 QR 碼。 IronBarcode 不依賴 .NET 6 及更高版本中Windows 特有的System.Drawing.Common 和 .NET Graphics API,因此可以實現跨平台功能,並具有更高的原始碼相容性。
IronBarcode。
IronBarcode是一個流行的 .NET 條碼庫,它提供了在 .NET 應用程式中建立、讀取和操作條碼圖像的各種功能。 該程式庫由 Iron Software 開發和維護,Iron Software 是一家專門從事 .NET 元件和程式庫的軟體開發公司。 IronBarcode 支援多種條碼格式,包括 Code 128、Code 39、QR 碼、Data Matrix 和 PDF417。該庫還提供了生成具有自訂尺寸、顏色和字體的條碼的功能,以及在條碼圖像中添加文字和徽標的功能。
除了產生條碼外,IronBarcode 還包含讀取和解碼條碼影像的功能。 該圖書館可以讀取和解碼影像、PDF 文件和即時攝影機畫面中的條碼。 它支援一維和二維條碼格式,甚至可以識別部分遮蔽或損壞的條碼。
先決條件
在 .NET 應用程式中使用 IronBarcode 之前,需要滿足一些先決條件。
- .NET Framework 或 .NET Core: IronBarcode 設計為與 .NET Framework 和 .NET Core 搭配使用。 請確保您的開發環境已安裝合適的 .NET 版本。
- Visual Studio: IronBarcode 可以與 Visual Studio 集成,方便開發和測試。 可以使用 Visual Studio 社群版、專業版或企業版。 可從Visual Studio 網站下載。
-
IronBarcode 庫:從Iron Software 網站或透過 NuGet 套件管理器下載並安裝 IronBarcode 庫。 可以使用 NuGet 套件管理員控制台執行以下命令來安裝該庫:
Install-Package BarCode。
建立一個新的 ASP.NET MVC 項目
開啟 Visual Studio,然後按一下"建立新專案"。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 1
在新視窗中,找到並選擇"ASP.NET MVC(Web 應用程式)模型視圖控制器",然後按一下"下一步"按鈕。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 2
輸入新項目的名稱和位置,然後按一下"下一步"。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 3
選擇要使用的 .NET 版本,其他選項保持不變,然後按一下"建立"。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 4
已建立一個.NET專案。
安裝 IronBarcode
1. 使用 NuGet 套件管理器
Visual Studio 中提供了此選項,它會將 IronBarcode 套件直接安裝到您的解決方案中。 開啟工具選單,點選 NuGet 套件管理器,如圖所示。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 6
在 NuGet 套件管理器中使用搜尋框尋找 IronBarcode 庫。 從可用軟體包清單中選擇 IronBarcode 選項。
2. 使用 Visual Studio 命令列
在 Visual Studio 選單中,前往"工具">"NuGet 套件管理員">"套件管理員控制台"。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 8
在套件管理器控制台標籤中輸入以下行:Install-Package BarCode。
該軟體包將下載/安裝到目前專案中,即可使用。
使用 IronBarcode 產生和顯示條碼影像
現在環境已經建置完畢,我們可以開始寫程式碼,在 ASP.NET MVC 中動態產生條碼影像了。
首先,在模型資料夾下建立一個名為 GenerateBarcodeModel.cs 的類
using System.ComponentModel.DataAnnotations;
namespace GenerateBarcodeMVCCore6_Demo.Models
{
public class GenerateBarcodeModel
{
[Display(Name = "Enter Barcode Text")]
public string Barcode { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace GenerateBarcodeMVCCore6_Demo.Models
{
public class GenerateBarcodeModel
{
[Display(Name = "Enter Barcode Text")]
public string Barcode { get; set; }
}
}
Imports System.ComponentModel.DataAnnotations
Namespace GenerateBarcodeMVCCore6_Demo.Models
Public Class GenerateBarcodeModel
<Display(Name := "Enter Barcode Text")>
Public Property Barcode() As String
End Class
End Namespace
在 wwwroot 資料夾下方建立一個名為"GeneratedBarcode"的資料夾,用於儲存產生的條碼影像。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 10
在"controllers"資料夾中的 HomeController.cs 類別中加入以下操作方法。
using Microsoft.AspNetCore.Mvc;
using IronBarCode;
using System;
using System.Drawing;
using System.IO;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
private readonly IWebHostEnvironment _environment;
public HomeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult CreateBarcode()
{
return View();
}
// Handling POST operation inside this Action method
[HttpPost]
public IActionResult CreateBarcode(GenerateBarcodeModel generateBarcode)
{
try
{
// Create a barcode using the input text
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(generateBarcode.Barcode, BarcodeWriterEncoding.Code128);
// Adding annotation text to barcode
barcode.AddBarcodeValueTextBelowBarcode();
// Styling the Barcode
barcode.ResizeTo(400, 120);
barcode.ChangeBarCodeColor(Color.Red);
barcode.SetMargins(10);
// Define path to save the barcode image
string path = Path.Combine(_environment.WebRootPath, "GeneratedBarcode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Save the generated barcode as a PNG file
string filePath = Path.Combine(_environment.WebRootPath, "GeneratedBarcode/barcode.png");
barcode.SaveAsPng(filePath);
// Get the file name and URL for the generated barcode image
string fileName = Path.GetFileName(filePath);
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedBarcode/{fileName}";
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception)
{
throw;
}
return View();
}
}
}
using Microsoft.AspNetCore.Mvc;
using IronBarCode;
using System;
using System.Drawing;
using System.IO;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
private readonly IWebHostEnvironment _environment;
public HomeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult CreateBarcode()
{
return View();
}
// Handling POST operation inside this Action method
[HttpPost]
public IActionResult CreateBarcode(GenerateBarcodeModel generateBarcode)
{
try
{
// Create a barcode using the input text
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(generateBarcode.Barcode, BarcodeWriterEncoding.Code128);
// Adding annotation text to barcode
barcode.AddBarcodeValueTextBelowBarcode();
// Styling the Barcode
barcode.ResizeTo(400, 120);
barcode.ChangeBarCodeColor(Color.Red);
barcode.SetMargins(10);
// Define path to save the barcode image
string path = Path.Combine(_environment.WebRootPath, "GeneratedBarcode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Save the generated barcode as a PNG file
string filePath = Path.Combine(_environment.WebRootPath, "GeneratedBarcode/barcode.png");
barcode.SaveAsPng(filePath);
// Get the file name and URL for the generated barcode image
string fileName = Path.GetFileName(filePath);
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedBarcode/{fileName}";
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception)
{
throw;
}
return View();
}
}
}
Imports Microsoft.AspNetCore.Mvc
Imports IronBarCode
Imports System
Imports System.Drawing
Imports System.IO
Namespace YourNamespace.Controllers
Public Class HomeController
Inherits Controller
Private ReadOnly _environment As IWebHostEnvironment
Public Sub New(ByVal environment As IWebHostEnvironment)
_environment = environment
End Sub
Public Function CreateBarcode() As IActionResult
Return View()
End Function
' Handling POST operation inside this Action method
<HttpPost>
Public Function CreateBarcode(ByVal generateBarcode As GenerateBarcodeModel) As IActionResult
Try
' Create a barcode using the input text
Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode(generateBarcode.Barcode, BarcodeWriterEncoding.Code128)
' Adding annotation text to barcode
barcode.AddBarcodeValueTextBelowBarcode()
' Styling the Barcode
barcode.ResizeTo(400, 120)
barcode.ChangeBarCodeColor(Color.Red)
barcode.SetMargins(10)
' Define path to save the barcode image
Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedBarcode")
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
' Save the generated barcode as a PNG file
Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedBarcode/barcode.png")
barcode.SaveAsPng(filePath)
' Get the file name and URL for the generated barcode image
Dim fileName As String = System.IO.Path.GetFileName(filePath)
Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}/GeneratedBarcode/{fileName}"
ViewBag.QrCodeUri = imageUrl
Catch e1 As Exception
Throw
End Try
Return View()
End Function
End Class
End Namespace
上述程式碼中的操作方法將處理稍後我們將建立的視圖產生的提交請求。 使用 IronBarcode,您可以自訂條碼格式、圖像元素、條碼字體和 HTML 圖像元素。 如需進行更多自訂,可能需要其他程式庫,例如用於安裝條碼字體的Iron Drawing 程式庫。 更詳細的API文件請點擊此處查看。
現在我們可以為條碼產生器方法建立一個視圖。
在 HomeController.cs 檔案中,右鍵點選 CreateBarcode 方法,然後按一下"新增檢視"。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 11
選擇 Razor View,然後按一下新增。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 12
根據下圖所示選擇參數,然後按一下"新增"。 它會自動為該方法新增一個視圖。
如何在 ASP.NET MVC 中動態產生和顯示條碼:圖 13
您可以修改產生的程式碼,根據需要更改介面。
@model GenerateBarcodeMVCCore6_Demo.Models.GenerateBarcodeModel
@{
ViewData["Title"] = "CreateBarcode";
}
<h1>CreateBarcode</h1>
<form asp-action="CreateBarcode" method="post">
<div>
<label asp-for="Barcode"></label>
<input asp-for="Barcode" />
<span asp-validation-for="Barcode"></span>
</div>
<button type="submit">Generate Barcode</button>
</form>
@if (ViewBag.QrCodeUri != null)
{
<div>
<img src="@ViewBag.QrCodeUri" alt="Barcode Image" />
</div>
}
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
現在一切都設置好了,只需打開 _Layout.cshtml 文件,並添加代碼以在 navbar 中添加 CreateBarcode 選項。
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Home" asp-action="CreateBarcode">CreateBarcode</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Home" asp-action="CreateBarcode">CreateBarcode</a>
</li>
現在運行該應用程式,在文字字段中輸入文字,然後單擊"生成條碼"按鈕,它將動態創建並顯示條碼圖像。
5.1 輸出
6.結論
在 ASP.NET MVC 應用程式中動態生成和顯示條碼圖像可以使用 IronBarcode 程式庫來實現——這是一個功能強大的 .NET 條碼圖像。 透過滿足安裝 .NET 框架、Visual Studio 和 IronBarcode 程式庫等先決條件,開發人員可以輕鬆建立 ASP.NET MVC 項目,並產生和顯示各種格式的條碼影像,例如 Code 39、Code 128 和 QR 碼。 IronBarcode庫為開發人員提供了產生具有自訂尺寸、顏色和字體的條碼的功能,以及為條碼圖像添加文字和徽標的功能。 除了產生條碼外,IronBarcode 還包含讀取和解碼條碼影像的功能。 借助 IronBarcode,開發人員可以輕鬆創建功能強大且動態的 Web 應用程式,以滿足其業務需求。 有關此主題的相關教程,請造訪以下連結。 有關條碼和二維碼產生的詳細步驟教程,請參閱以下連結。
常見問題解答
如何在 ASP.NET MVC 中動態生成條碼圖像?
您可以使用 IronBarcode 庫在 ASP.NET MVC 中動態生成條碼圖像,通過將其 API 集成到您的專案中。這個 C# 庫支持多種條碼格式,並允許在尺寸、顏色和文字方面進行自定義。
在 ASP.NET MVC 應用程序中使用 IronBarcode 的好處是什麼?
IronBarcode 提供跨平台功能,無需依賴於 Windows 特定的 .NET Graphics API。它支持多種條碼格式,提供自定義選項,並可以從圖像、PDF 和實時攝像頭饋送中讀取和解碼條碼。
如何在 ASP.NET MVC 專案中集成 IronBarcode?
要在 ASP.NET MVC 專案中集成 IronBarcode,您需要使用 Visual Studio 中的 NuGet 套件管理器安裝庫,為條碼數據設置模型,創建控制器以處理條碼生成,並設計一個視圖來進行用戶交互和條碼顯示。
在 ASP.NET MVC 中使用 IronBarcode 生成支持哪些條碼格式?
IronBarcode 支持在 ASP.NET MVC 中生成多種條碼格式,包括 Code 39、Code 128、QR Code、Data Matrix 和 PDF417。
我可以自定義使用 IronBarcode 生成的條碼圖像的外觀嗎?
可以,IronBarcode 允許自定義條碼圖像,包括調整條碼格式、顏色、尺寸、字體,並添加文字或標誌到條碼中。
在 ASP.NET MVC 中生成條碼時如何排除故障?
如果在 ASP.NET MVC 中生成條碼時遇到問題,請確保正確安裝了 IronBarcode 庫,滿足所有依賴項,並正確實施條碼數據模型和控制器設置。請參考 IronBarcode 的文檔以獲取更多指導。
是否可以使用 IronBarcode 在 ASP.NET MVC 應用程序中解碼條碼?
可以,IronBarcode 包含從多個來源(如圖像、PDF 文檔和實時攝像頭饋送)解碼條碼的功能,即使它們部分損壞。
使用 IronBarcode 設置 ASP.NET MVC 專案的先決條件是什麼?
您需要安裝 .NET Framework 或 .NET Core、Visual Studio 以及可以從 Iron Software 網站下載或通過 NuGet 套件管理器安裝的 IronBarcode 庫。

