如何在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 中動態產生 BarCode 影像?
您可以使用 IronBarcode library 在 ASP.NET MVC 中動態生成條碼圖像,方法是將其 API 整合到您的專案中。此 C# 程式庫支援各種條碼格式,並允許在尺寸、顏色和文字方面進行自訂。
在 ASP.NET MVC 應用程式中使用 IronBarcode 有什麼好處?
IronBarcode for .NET 提供跨平台功能,而無需依賴 Windows 特定的 .NET 圖形 API。它支援多種條碼格式,提供客製化選項,並可從影像、PDF 檔案和即時攝影機訊號中讀取和解碼條碼。
如何將 IronBarcode 整合到 ASP.NET MVC 專案中?
要將 IronBarcode 整合到 ASP.NET MVC 專案中,您需要在 Visual Studio 中透過 NuGet Package Manager 安裝函式庫,設定條碼資料的模型,建立控制器以處理條碼產生,並設計用戶互動和條碼顯示的視圖。
使用 IronBarcode 在 ASP.NET MVC 中生成条码支持哪些条码格式?
IronBarcode 支持在 ASP.NET MVC 中生成多种条形码格式,包括 Code 39、Code 128、QR Code、Data Matrix 和 PDF417。
我可以定制用 IronBarcode 生成的条码图像的外观吗?
是的,IronBarcode 允許自訂條碼影像,包括調整條碼格式、顏色、尺寸、字型,以及在條碼中加入文字或標誌。
在 ASP.NET MVC 中生成 BarCode 時,如何排除故障?
如果您在 ASP.NET MVC 中生成条码时遇到问题,请确保 IronBarcode 库已正确安装,满足所有依赖关系,条码数据模型和控制器设置已正确实现。請參考 IronBarcode 的說明文件以獲得更多指導。
IronBarcode for .NET 是否可以在 ASP.NET MVC 應用程式中解碼條碼?
是的,IronBarcode 包括解碼來自不同來源的 BarCode 的功能,例如圖像、PDF 文件和即時攝影機訊號,即使它們有部分損壞。
使用 IronBarcode 建立 ASP.NET MVC 專案的先決條件是什麼?
您需要安裝 .NET Framework 或 .NET Core、Visual Studio 以及 IronBarcode 函式庫,該函式庫可從 Iron Software 網站下載或透過 NuGet Package Manager 安裝。









