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 bar code 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.

  1. .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.

  2. 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.

  3. 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.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 1

In the new window find and select "ASP.NET MVC (Web App) Model View Controller" and click on the Next button.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 2

Click write the name of the new project and its location and click on next.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 3

Select the .NET version you want to use and leave all other options as it is and click Create.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 4

A .NET project is created.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 5

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.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 6

Search for the IronBarcode library by using the search box in NuGet Package Manager. Select the IronBarcode option from the list of available packages.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 7

2. Using the Visual Studio Command-Line

In the Visual Studio menu, Go to Tools > NuGet Package Manager > Package Manager console.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 8

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.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 9

Generating and Displaying Barcode Images Using IronBarcode

Now our environment is set up, we can get started on how to write code to generate 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
VB   C#

Create a folder named "GeneratedBarcode" under the wwwroot folder to store generated barcode image.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 10

Add the following action method in your "HomeController.cs" class in the "controllers" folder.


    public IActionResult CreateBarcode()
            {
                return View();
            }

            //  handling POST operation Inside this Action method
            [HttpPost]
            public IActionResult CreateBarcode(GenerateBarcodeModel generateBarcode)
            {
                try
                {
                    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);

                    string path = Path.Combine(_environment.WebRootPath, "GeneratedBarcode");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string filePath = Path.Combine(_environment.WebRootPath, "GeneratedBarcode/barcode.png");

            // The generated barcode object can be manipulated, annotated, and exported as an image file, a bitmap image, a PDF file, or a data stream.
            // Here, we save the generated barcode as an image to the GeneratedBarcode folder we had created
                    barcode.SaveAsPng(filePath);
                    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();
            }

    public IActionResult CreateBarcode()
            {
                return View();
            }

            //  handling POST operation Inside this Action method
            [HttpPost]
            public IActionResult CreateBarcode(GenerateBarcodeModel generateBarcode)
            {
                try
                {
                    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);

                    string path = Path.Combine(_environment.WebRootPath, "GeneratedBarcode");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string filePath = Path.Combine(_environment.WebRootPath, "GeneratedBarcode/barcode.png");

            // The generated barcode object can be manipulated, annotated, and exported as an image file, a bitmap image, a PDF file, or a data stream.
            // Here, we save the generated barcode as an image to the GeneratedBarcode folder we had created
                    barcode.SaveAsPng(filePath);
                    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();
            }
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
					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)

					Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedBarcode")
					If Not Directory.Exists(path) Then
						Directory.CreateDirectory(path)
					End If
					Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedBarcode/barcode.png")

			' The generated barcode object can be manipulated, annotated, and exported as an image file, a bitmap image, a PDF file, or a data stream.
			' Here, we save the generated barcode as an image to the GeneratedBarcode folder we had created
					barcode.SaveAsPng(filePath)
					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
VB   C#

The action method in the code above will handle the submit request generated from 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 "HomeController.cs" file, right-click on the createBarcode method and click on Add View.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 11

Select Razor View and click add.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 12

Select the parameters as shown in the below image and click on add, it will automatically add view for that method.

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 13

You can modify the generated code to change the interface as you want.


    @model GenerateBarcodeMVCCore6_Demo.Models.GenerateBarcodeModel

    @{
        ViewData["Title"] = "CreateBarcode";
    }

    CreateBarcode

    GenerateBarcodeModel

        Back to List

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

    @model GenerateBarcodeMVCCore6_Demo.Models.GenerateBarcodeModel

    @{
        ViewData["Title"] = "CreateBarcode";
    }

    CreateBarcode

    GenerateBarcodeModel

        Back to List

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
model ReadOnly Property () As GenerateBarcodeMVCCore6_Demo.Models.GenerateBarcodeModel
		ViewData("Title") = "CreateBarcode"
End Property

	CreateBarcode GenerateBarcodeModel Back [to] List ReadOnly Property Scripts() As section
		@
		If True Then
			Await Html.RenderPartialAsync("_ValidationScriptsPartial")
		End If
	End Property
VB   C#

Now everything is set up, just open the _Layout.cshtml file and add the code to add the CreateBarcode option in the navbar.

CreateBarcode
CreateBarcode
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'CreateBarcode
VB   C#

Now run the application, write text in the text field, and click on Generate barcode button, and it will create and show the bar code image Dynamically.

5.1. Output

How to Dynamically Generate and Display Barcode in ASP.NET MVC: Figure 14

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 .NET framework, Visual Studio, and 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.