How to Dynamically Generate and Display Barcode in ASP.NET MVC
ASP.NET MVC is a popular web development framework that allows developers to build robust and dynamic web applications. A common requirement in web applications is the ability to generate and display barcode images. Barcode images are used to represent data in a machine-readable format and can be read by a barcode scanner.
Dynamically generating and displaying barcode images in ASP.NET MVC can be achieved using the market-leading C# library, IronBarcode. This library provides APIs that enable developers to easily generate barcode images across platforms in various formats such as Code 39, Code 128, and QR Code. Without relying on System.Drawing.Common
and .NET Graphics API, which are Windows-specific from .NET 6, IronBarcode allows cross-platform functionalities and allows for more source compatibility.
IronBarcode
IronBarcode is a popular .NET barcode library that provides a wide range of features for creating, reading, and manipulating barcode images in .NET applications. The library is developed and maintained by Iron Software, a software development company that specializes in .NET components and libraries. IronBarcode provides support for a wide range of barcode formats including Code 128, Code 39, QR Code, Data Matrix, and PDF417. The library also provides features for generating barcodes with custom dimensions, colors, and fonts, and for adding text and logos to barcode images.
In addition to barcode generation, IronBarcode also includes features for reading and decoding barcode images. The library can read and decode barcodes from images, PDF documents, and live camera feeds. It supports both 1D and 2D barcode formats and can even recognize barcodes that are partially obscured or damaged.
Prerequisites
Before working with IronBarcode in a .NET application, there are a few prerequisites that need to be satisfied.
- .NET Framework or .NET Core: IronBarcode is designed to work with both .NET Framework and .NET Core. Make sure that your development environment has the appropriate .NET version installed.
- Visual Studio: IronBarcode can be integrated with Visual Studio for easy development and testing. Visual Studio Community, Professional, or Enterprise editions can be used. It can be downloaded from the Visual Studio website.
IronBarcode Library: Download and install the IronBarcode library from the Iron Software website or via the NuGet package manager. The library can be installed using the NuGet Package Manager Console by running the following command:
Install-Package BarCode
.IronBarcode is free for development but must be licensed for commercial and deployment purposes. You can try the free trial to test all its functionality.
Creating a New ASP.NET MVC Project
Open Visual Studio and click on Create a new project.
In the new window, find and select "ASP.NET MVC (Web App) Model View Controller" and click on the Next button.
Enter the name of the new project and its location and click on Next.
Select the .NET version you want to use and leave all other options as they are and click Create.
A .NET project is created.
Install IronBarcode
1. Using NuGet Package Manager
This option is available within Visual Studio and will install the IronBarcode package directly to your solution. Go to tools and click on NuGet Package Manager as shown.
Search for the IronBarcode library by using the search box in NuGet Package Manager. Select the IronBarcode option from the list of available packages.
2. Using the Visual Studio Command-Line
In the Visual Studio menu, go to Tools > NuGet Package Manager > Package Manager console.
Enter the following line in the package manager console tab: Install-Package BarCode
.
The package will download/install to the current project and be ready for use.
Generating and Displaying Barcode Images Using IronBarcode
Now our environment is set up, we can get started on how to write code to generate a barcode image in ASP.NET MVC dynamically.
First, create a class under the model folder named 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
Create a folder named "GeneratedBarcode" under the wwwroot
folder to store generated barcode images.
Add the following action method in your HomeController.cs
class in the "controllers" folder.
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
The action method in the code above will handle the submit request generated from the View that we will create later. With IronBarcode, you can customize the barcode format, image element, barcode font, and HTML image element. Additional libraries might be required for more customization, such as Iron Drawing for installing barcode font. More detailed API documentation can be found here.
Now we can create a view for our barcode generator method.
In the HomeController.cs
file, right-click on the CreateBarcode
method and click on Add View.
Select Razor View and click add.
Select the parameters as shown in the below image and click on Add. It will automatically add a view for that method.
You can modify the generated code to change the interface as you want.
@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");}
}
Now everything is set up, just open the _Layout.cshtml
file and add the code to add the CreateBarcode
option in the navbar
.
<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>
Now run the application, write text in the text field, and click on the Generate barcode button, and it will create and show the barcode image dynamically.
5.1. Output
6. Conclusion
Generating and displaying barcode images dynamically in ASP.NET MVC applications can be achieved using the IronBarcode library - a powerful .NET barcode library that provides a wide range of features for creating, reading, and manipulating barcode images in .NET applications. By satisfying prerequisites such as installing the .NET framework, Visual Studio, and the IronBarcode library, developers can easily create ASP.NET MVC projects and generate and display barcode images in various formats such as Code 39, Code 128, and QR Code. The IronBarcode library provides developers with features for generating barcodes with custom dimensions, colors, and fonts, and for adding text and logos to barcode images. In addition to barcode generation, IronBarcode also includes features for reading and decoding barcode images. With IronBarcode, developers can easily create powerful and dynamic web applications that meet their business needs. For a related tutorial on this topic visit the following link. For a step-by-step tutorial on barcode and QR code generation, please refer to the following link.
Frequently Asked Questions
What is ASP.NET MVC?
ASP.NET MVC is a popular web development framework that allows developers to build robust and dynamic web applications.
How can barcode images be dynamically generated and displayed in ASP.NET MVC?
Dynamically generating and displaying barcode images in ASP.NET MVC can be achieved using the C# library, IronBarcode, which provides APIs to generate barcode images in various formats across platforms.
What barcode formats does the library support?
IronBarcode supports a wide range of barcode formats including Code 128, Code 39, QR Code, Data Matrix, and PDF417.
What are the prerequisites for using the library in a .NET application?
The prerequisites include having the .NET Framework or .NET Core installed, using Visual Studio, and downloading and installing the IronBarcode library from the Iron Software website or via the NuGet package manager.
Is the library free to use?
IronBarcode is free for development but must be licensed for commercial and deployment purposes. A free trial is available to test its functionality.
How do you install the library using NuGet Package Manager?
Within Visual Studio, use the NuGet Package Manager to search for the IronBarcode library and install it directly to your solution.
Can the library read and decode barcode images?
Yes, IronBarcode includes features for reading and decoding barcodes from images, PDF documents, and live camera feeds.
What customization options does the library offer for barcode generation?
IronBarcode allows customization of barcode format, image elements, barcode font, colors, and dimensions. It also supports adding text and logos to barcode images.
How do you create a new ASP.NET MVC project to generate barcodes?
In Visual Studio, create a new project by selecting 'ASP.NET MVC (Web App) Model View Controller' and follow the setup prompts to establish the project environment.
What steps are involved in generating a barcode image with the library in ASP.NET MVC?
Create a model for the barcode, set up a controller with action methods to handle barcode generation, and create a view to interface with the user for input and barcode display.