ASP.NET MVC QR Code Generator

Introduction

This article discusses dynamically generating QR codes in ASP.NET MVC. It covers generating QR codes, creating QR code images, and working with QR code-related tasks in ASP.NET MVC using a library called IronBarCode.

You can install this library via Visual Studio's NuGet package manager to enable dynamic QR code generation, QR code text creation, reading QR codes, and image creation in ASP.NET MVC.

I will walk you through the steps to generate a QR code image from the generated QR code text. 

Cross-Platform Support

IronBarcode is designed for use with C#, F#, and VB.NET, and it can run on .NET 7, 6, 5, Core, Standard, or .NET Framework.

Creating a New Project in Visual Studio 2022

  1. Launch Visual Studio and select Create a New Project.
    Create New Project

Create a Web App

  1. In the Create a New Project dialog, select ASP.NET Web Application (.NET Framework).

  2. Configure your new project by entering the project name as "IronQRCode_Demo," choosing a location, and setting the solution name. Select .NET Framework 4.8 and click Create.
    Configure your new Project

Create a New ASP.NET Web Application

Select the MVC (Model-View-Controller) template from the Create New ASP.NET Web Application dialog and click Create.

Create a New ASP.NET Web Application

Visual Studio will create a new MVC web application for you

Find and Install NuGet Packages

Install the Barcode Library through NuGet Package Manager

  1. Go to Project > Manage NuGet Packages.

  2. On the NuGet Package Manager page, choose nuget.org as the Package source.

  3. Under the Browse tab, search for IronBarcode, select BarCode from the list, and then click Install.

  4. If prompted to verify the installation, select OK.
    Serach IronBarCode NuGet Package

Using the Visual Studio Command-Line

  1. In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console.

  2. In the package manager console tab, enter the following command:

Install-Package IronBarCode

This will download and install the package into your current project, making it ready for use.

Package manager console

Add a data model class

Right-click the Models folder > Add > Class. Name the file QRCodeModel.cs.

using System.ComponentModel.DataAnnotations;

namespace IronQRCode_Demo.Models
{
    public class QRCodeModel
    {
        [Display]
        [Required]
        public string QRCodeText { get; set; }
    }
}

Add a Controller

  1. In Solution Explorer, right-click Controllers > Add > Controller.

  2. In the Add New Scaffolded Item dialog box, select MVC Controller - Empty > Add.

  3. In the Add New Item - IronQRCode_Demo dialog, enter HomeController.cs and select Add.

I will use the existing HomeController to write the code.

Add New Scaffolded Item

using IronBarCode;
using IronQRCode_Demo.Models;
using System;
using System.Drawing;
using System.IO;
using System.Web.Mvc;

namespace IronQRCode_Demo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

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

        [HttpPost]
        public ActionResult CreateQRCode(QRCodeModel qrCodeModel)
        {
            try
            {
                GeneratedBarcode qrcode = QRCodeWriter.CreateQrCode(qrCodeModel.QRCodeText, 200);
                qrcode.AddBarcodeValueTextBelowBarcode();
                // Styling a QR code and adding annotation text
                qrcode.SetMargins(10);
                qrcode.ChangeBarCodeColor(Color.BlueViolet);
                string path = Path.Combine(Server.MapPath("~/GeneratedQRCode"));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string filePath = Path.Combine(Server.MapPath("~/GeneratedQRCode/qrcode.png"));
                qrcode.SaveAsPng(filePath);
                string fileName = Path.GetFileName(filePath);

                //http://localhost:59564/GeneratedQRCode/qrcode.png

                string imageUrl = $"{this.Request.Url.Scheme}://{this.Request.Url.Host}:{this.Request.Url.Port}" + "/GeneratedQRCode/" + fileName;
                ViewBag.QRCodeCodeUri = imageUrl;
            }
            catch (Exception)
            {
                throw;
            }
            return View();
        }
    }
}

Add a View

  1. Right-click on the Views folder, then Add > New Folder and name the folder Home. I will use the existing Home folder.
  2. Right-click on the Views/Home folder, and then Add > New Item or choose View.
  3. Select MVC5 View from the Add new Scaffold item dialog.
  4. Enter View the name,
  5. Select Create template
  6. Select Model class QRCodeModel (IronQRCode_Demo.Models) from the Add view dialog
  7. Select Show All Templates.
  8. Select Add
  9. Replace the code in the CreateQRCode View.

Add view

@model IronQRCode_Demo.Models.QRCodeModel

@{
    ViewBag.Title = "CreateQRCode";
}

<h2>CreateQRCode</h2>


@using (Html.BeginForm("CreateQRCode", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <div class="form-group">
            @Html.LabelFor(model => model.QRCodeText, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="input-group mb-3">
                @Html.EditorFor(model => model.QRCodeText, new { htmlAttributes = new { @class = "form-control rounded-0" } })
                <div class="input-group-append">
                    <input type="submit" value="Create" class="btn btn-primary rounded-0" />
                </div>
            </div>
            @Html.ValidationMessageFor(model => model.QRCodeText, "", new { @class = "text-danger" })
        </div>
        @if (@ViewBag.QRCodeCodeUri != null)
        {
            <img src="@ViewBag.QRCodeCodeUri" />
        }
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Run the Application

Select Ctrl+F5 to run the app without the debugger. Visual Studio runs the app and opens the default browser.

Create QR Code

Conclusion

In conclusion, we have generated a QRCode image. We can save QRCode as JPG, PNG images, PDF, or HTML files in ASP.NET MVC. We can also add a logo to our QRCode file in ASP.NET MVC.


Similar Articles