USING IRONBARCODE

How to Generate QR Codes in ASP.NET MVC

In today's fast-paced digital landscape, the generation of QR codes has become an essential tool for efficient information sharing. These compact, two-dimensional barcodes, capable of storing a wide range of data, including URLs, text, contact information, product details, and much more, play a pivotal role in modern communication. Incorporating QR code generation capabilities into your ASP.NET MVC application allows you to empower users by seamlessly generating QR codes and enhancing their experience, streamlining interactions, and facilitating the effortless exchange of information.

If you're developing an ASP.NET MVC application and want to incorporate QR code generation capabilities, IronBarcode is an excellent library that simplifies the process. In this article, we will explore how to generate QR codes in ASP.NET MVC using the Iron Barcode library.

IronBarcode

IronBarcode is a powerful and feature-rich QR Code generation and recognition library for .NET applications. With IronBarcode, developers can easily integrate barcode and QR Code functionality into their ASP.NET MVC projects, including the ability to generate QR codes. The library provides a comprehensive set of tools and APIs that simplify the process of creating and customizing QR codes, allowing developers to tailor them to their specific requirements.

IronBarcode offers extensive support for various barcode types, including QR codes, making it an ideal choice for projects that require QR code generation capabilities. It provides developers with the flexibility to specify the data to be encoded, control the size and resolution of the generated QR codes, and even add visual styling elements such as colors and logos. The library ensures high-quality barcode generation with precise control over every aspect of the QR code's appearance.

Beyond QR code generation, IronBarcode also includes robust features for barcode reading and decoding. It supports scanning and extracting data from QR codes, enabling applications to process information encoded within them. This functionality is beneficial for scenarios where barcode scanning and data extraction are necessary, such as inventory management, ticketing systems, and mobile applications.

Now, let's create a project to generate a QR code in the ASP.NET Core MVC Web app.

Setting Up the Project

Before we delve into the implementation details, let's ensure that your ASP.NET MVC project is set up and ready to go. Whether you're starting a new project or working with an existing one, the steps outlined below will guide you through the process of integrating the Iron Barcode library into your application. In my case, I have created a new project.

Steps for creating a new project are as follows:

  1. Open Microsoft Visual Studio 2022.
  2. On the start page, click on "Create a new project" or go to "File" > "New" > "Project" from the top menu.
  3. In the "Create a new project" window, you'll see different project templates to choose from. Choose the project template "ASP.NET Core web app (Model-view-controller)" and click "Next."
  4. Enter a name and location for your project. Choose a suitable location on your computer to save the project files.
  5. Select the desired framework version. Visual Studio usually suggests the latest stable version, but you can choose a different one if needed. I have chosen .NET 7.
  6. Customize any additional project settings, such as authentication options or project folders, based on your requirements.
  7. Click "Create" to create the project.

Visual Studio will then generate the project files and open the solution explorer, where you can see the project structure and start working on your code.

How to Generate QR Codes in ASP.NET MVC: Figure 1

Now, we need to install Iron Barcode Library into our application.

Install Iron Barcode

To begin, open the Package Manager Console in Visual Studio and run the following command:

Install-Package IronBarCode

This command will install the Iron Barcode library and add the necessary references to your project.

How to Generate QR Codes in ASP.NET MVC: Figure 2

Now, let's write some code to create QR codes.

Create QRCodeModel

Create a Model Class inside the Models folder and write the following code:

using System.ComponentModel.DataAnnotations;

public class QRCodeModel
{
    [Display(Name = "Enter QR Code Text")]
    public string QRCodeText { get; set; }
}
using System.ComponentModel.DataAnnotations;

public class QRCodeModel
{
    [Display(Name = "Enter QR Code Text")]
    public string QRCodeText { get; set; }
}
Imports System.ComponentModel.DataAnnotations

Public Class QRCodeModel
	<Display(Name := "Enter QR Code Text")>
	Public Property QRCodeText() As String
End Class
$vbLabelText   $csharpLabel

Create QR Code Controller

In your ASP.NET MVC project, create a new controller named QrCodeController. To do this, right-click on the Controllers folder in your project's structure, select "Add," and then choose "Controller." From the available options, select "MVC Controller - Empty".

Write the following code in QrCodeController:

using Microsoft.AspNetCore.Mvc;
using IronBarCode;
using System.IO;

public class QrCodeController : Controller
{
    private readonly IWebHostEnvironment _environment;

    public QrCodeController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

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

    [HttpPost]
    public IActionResult CreateQRCode(QRCodeModel generateQRCode)
    {
        try
        {
            // Creating QR Code
            GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText);
            string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string filePath = Path.Combine(path, "qrcode.png");
            barcode.SaveAsPng(filePath);

            string fileName = Path.GetFileName(filePath);
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedQRCode/{fileName}";

            ViewBag.QrCodeUri = imageUrl;
        }
        catch (Exception ex)
        {
            // Handle exceptions
            // Log the exception details here for troubleshooting and debugging.
            throw;
        }

        return View();
    }
}
using Microsoft.AspNetCore.Mvc;
using IronBarCode;
using System.IO;

public class QrCodeController : Controller
{
    private readonly IWebHostEnvironment _environment;

    public QrCodeController(IWebHostEnvironment environment)
    {
        _environment = environment;
    }

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

    [HttpPost]
    public IActionResult CreateQRCode(QRCodeModel generateQRCode)
    {
        try
        {
            // Creating QR Code
            GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText);
            string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string filePath = Path.Combine(path, "qrcode.png");
            barcode.SaveAsPng(filePath);

            string fileName = Path.GetFileName(filePath);
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedQRCode/{fileName}";

            ViewBag.QrCodeUri = imageUrl;
        }
        catch (Exception ex)
        {
            // Handle exceptions
            // Log the exception details here for troubleshooting and debugging.
            throw;
        }

        return View();
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports IronBarCode
Imports System.IO

Public Class QrCodeController
	Inherits Controller

	Private ReadOnly _environment As IWebHostEnvironment

	Public Sub New(ByVal environment As IWebHostEnvironment)
		_environment = environment
	End Sub

	Public Function CreateQRCode() As IActionResult
		Return View()
	End Function

	<HttpPost>
	Public Function CreateQRCode(ByVal generateQRCode As QRCodeModel) As IActionResult
		Try
			' Creating QR Code
			Dim barcode As GeneratedBarcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText)
			Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedQRCode")

			If Not Directory.Exists(path) Then
				Directory.CreateDirectory(path)
			End If

			Dim filePath As String = System.IO.Path.Combine(path, "qrcode.png")
			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}/GeneratedQRCode/{fileName}"

			ViewBag.QrCodeUri = imageUrl
		Catch ex As Exception
			' Handle exceptions
			' Log the exception details here for troubleshooting and debugging.
			Throw
		End Try

		Return View()
	End Function
End Class
$vbLabelText   $csharpLabel

This code sets up a controller that can generate QR codes. When the CreateQRCode action is called, it takes the text for the QR code, generates the QR code image, saves it, and provides the URL for the image in the view for display. More detail is as follows:

  • The controller has a constructor that takes an IWebHostEnvironment parameter to access the web hosting environment.
  • The CreateQRCode action returns a view.
  • The CreateQRCode action with the [HttpPost] attribute takes a QRCodeModel parameter, which contains the QR code text.
  • Inside the action, a QR code is generated using the QRCodeWriter class from the Iron Barcode library.
  • The generated QR code is saved as a PNG image file in a folder called GeneratedQRCode in the web root path.
  • If the GeneratedQRCode folder doesn't exist, it is created.
  • The file path and URL for the saved QR code image are generated.
  • The URL of the QR code image is stored in the ViewBag.QrCodeUri property to be used in the view.
  • Any exceptions that occur during the process are caught and logged.

Add CreateQRCode View

Now, to add a new view, right-click on the CreateQRCode action method in the QrCodeController class. Select "Add View," then select "Razor View," and click on the "Add" button.

How to Generate QR Codes in ASP.NET MVC: Figure 3

A new window will appear as shown below.

How to Generate QR Codes in ASP.NET MVC: Figure 4

Write the view name, select template "Create," and select our newly created model class QRCodeModel. Click on Add Button. The view will be created. Replace your view with the below code.

@model QRCodeModel

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

<h1>Create QRCode in ASP.NET MVC</h1>

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateQRCode">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="QRCodeText" class="control-label"></label>
                <input asp-for="QRCodeText" class="form-control" />
                <span asp-validation-for="QRCodeText" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
            <div class="form-group">
                @if (ViewBag.QrCodeUri != null)
                {
                    <img src="@ViewBag.QrCodeUri" class="img-thumbnail" alt="Generated QR Code" />
                }
            </div>
        </form>
    </div>
</div>

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

Now, let's move to the Program.cs class and change the default Controller Route.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=QrCode}/{action=CreateQRCode}/{id?}"
);
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=QrCode}/{action=CreateQRCode}/{id?}"
);
app.MapControllerRoute(name:= "default", pattern:= "{controller=QrCode}/{action=CreateQRCode}/{id?}")
$vbLabelText   $csharpLabel

This will change the default route from HomeController to our QrCodeController.

Now, compile and run the project.

Output

How to Generate QR Codes in ASP.NET MVC: Figure 5

Enter text in the text box and click on the create button. A QR code will be created and displayed on the screen as shown below.

How to Generate QR Codes in ASP.NET MVC: Figure 6 - QR Code in ASP.NET

Now, let's add visual styling to our barcode by adding annotation text, QR Code value, and changing the QR Code color.

Add Visual Styling in QR Code

Add the following line of code inside the CreateQRCode Action method.

barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF");
barcode.AddBarcodeValueTextBelowBarcode();
barcode.ChangeBackgroundColor(System.Drawing.Color.White);
barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed);
barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF");
barcode.AddBarcodeValueTextBelowBarcode();
barcode.ChangeBackgroundColor(System.Drawing.Color.White);
barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed);
barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF")
barcode.AddBarcodeValueTextBelowBarcode()
barcode.ChangeBackgroundColor(System.Drawing.Color.White)
barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed)
$vbLabelText   $csharpLabel

Now, run the project and generate the QR Code.

How to Generate QR Codes in ASP.NET MVC: Figure 7 - Generate QR Code

Conclusion

In ASP.NET MVC, integrating IronBarcode is straightforward. It provides a user-friendly interface, making it easy to work with QR codes. By leveraging IronBarcode, you can enhance your application by adding QR code functionality, enabling users to share and access information conveniently. IronBarcode is a valuable library that simplifies the process of generating QR codes and reading QR codes in ASP.NET MVC. It empowers developers to create dynamic applications that utilize the power of QR codes for efficient data sharing and retrieval.

Iron Barcode is free for personal use. However, for commercial purposes, you need to buy its commercial license, which comes with a free trial. You may also get a significant discount if you get the complete Iron Suite. Iron Suite is a comprehensive collection of .NET software components designed to simplify development tasks and enhance functionality. It offers five powerful libraries, including Iron Barcode, IronOCR, IronPDF, IronXL, and Iron Webscraper that enable developers to work with barcodes, optical character recognition, PDF processing, Excel, and CSV files seamlessly. You will get all five products for the price of two if you opt to purchase the complete Iron Suite.

Frequently Asked Questions

What is IronBarcode?

IronBarcode is a powerful and feature-rich QR Code generation and recognition library for .NET applications, allowing developers to integrate barcode and QR Code functionality into their ASP.NET MVC projects.

How do I set up a new ASP.NET MVC project to generate QR codes?

To set up a new ASP.NET MVC project, open Microsoft Visual Studio, create a new project using the 'ASP.NET Core web app (Model-view-controller)' template, and install the IronBarcode library via the Package Manager Console using the command: Install-Package IronBarCode.

How can I generate a QR code in an ASP.NET MVC application?

To generate a QR code, create a QRCodeModel to capture input, set up a controller action to generate and save the QR code using IronBarcode's QRCodeWriter class, and display the generated QR code on a view.

What are some customization options available for QR codes?

IronBarcode allows customization such as specifying the data to be encoded, controlling size and resolution, adding visual styling elements like colors and logos, and adding annotation text above or below the barcode.

How can I display a generated QR code in an ASP.NET MVC view?

After generating a QR code, store its URL in the ViewBag and use an HTML image tag in your Razor view to display the image using the stored URL.

Can this library read and decode QR codes as well?

Yes, IronBarcode includes robust features for barcode reading and decoding, supporting scanning and extracting data from QR codes, useful for tasks like inventory management and ticketing systems.

Is this library free to use?

IronBarcode is free for personal use. For commercial purposes, a commercial license is required, which is available for purchase and comes with a free trial.

What is the Iron Suite?

The Iron Suite is a comprehensive collection of .NET software components, offering libraries like Iron Barcode, Iron OCR, Iron PDF, Iron XL, and Iron Webscraper, providing tools for barcode, OCR, PDF, Excel, and web scraping functionalities.

How do I change the default route in an ASP.NET MVC application?

To change the default route, modify the 'MapControllerRoute' method in the 'Program.cs' file to set the desired controller and action as the default.

What are some common use cases for QR codes in applications?

Common use cases for QR codes include inventory management, quick access to websites, contactless payment systems, ticketing, and mobile applications where rapid information exchange is required.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he says it’s one of his favorite aspects of working with Iron Software. Jordi grew up in Miami, Florida and studied Computer Science and Statistics at University of Florida.
< PREVIOUS
How to Generate Barcode in VB.NET
NEXT >
How to Generate QR Code in Blazor