Generate QR Code In ASP.NET Core MVC

Introduction

In this article, we are going to create an ASP.Net Core MVC application that generates QR Code for different purposes like Email, Website, Bookmark Websites, SMS, WhatsApp, etc. For this, we are going to use NuGet package called QRCoder.

Generate QR Code in ASP.Net Core MVC

About QRCoder NuGet Package

QRCoder is a simple library, written in C#.NET, which enables you to create QR codes. It hasn't any dependencies on other libraries and is available as .NET Framework and .NET Core PCL version on NuGet.

QRCoder provides many types of QR Codes but in this article, I will use only the following types.

  • URL
  • Bookmark Website
  • Send SMS
  • Send WhatsApp Message
  • Compose Email
  • Connect To WIFI

Create ASP.Net Core MVC project.

Step 1

Open Visual Studio and click on Create New Project.

Step 2

Select ASP.NET CORE Web App (Model-View-Controller) Template as shown in the below image and click on next button.

Generate QR Code in ASP.Net Core MVC

Step 3

Configure your project by specifying the name of the project and the location where you want to save your project.

Generate QR Code in ASP.Net Core MVC

Step 4

Select the version of the .Net Core framework you want to use and click on create button.

Add New Controller

Step 1

Right Click on Controller Folder then click on Add then Controller.

Generate QR Code in ASP.Net Core MVC

Step 2

Select MVC Empty Controller. And give a name whatever you want here I gave QRCode.

Generate QR Code in ASP.Net Core MVC

Add NuGet Package

Step 1

Right click on your project and then click on Manage NuGet Packages.

Generate QR Code in ASP.Net Core MVC

Step 2

Search for QRCoder in browse tab.

Generate QR Code in ASP.Net Core MVC

Step 3

Click on the install button and it will install in your project.

Create a new Model Class

For transferring data from controller to view and view to controller we have to use model class.

Step 1

For creating a model right click on the Model folder and click on Add then class.

Step 2

Give a suitable name for your class, Here I gave QRCodeModel.

Step 3

Create required properties in your class. As you can see in the below code I have created different properties for different types of QR Codes.

public class QRCodeModel {
    public int QRCodeType {
        get;
        set;
    }
    public string QRImageURL {
        get;
        set;
    }
    //for bookmark qr code
    public string BookmarkTitle {
        get;
        set;
    }
    public string BookmarkURL {
        get;
        set;
    }
    // for email qr codes
    public string ReceiverEmailAddress {
        get;
        set;
    }
    public string EmailSubject {
        get;
        set;
    }
    public string EmailMessage {
        get;
        set;
    }
    //for sms qr codes
    public string SMSPhoneNumber {
        get;
        set;
    }
    public string SMSBody {
        get;
        set;
    }
    //for website
    public string WebsiteURL {
        get;
        set;
    }
    // for whatsapp qr message code
    public string WhatsAppNumber {
        get;
        set;
    }
    public string WhatsAppMessage {
        get;
        set;
    }
    // for wifi qr code
    public string WIFIName {
        get;
        set;
    }
    public string WIFIPassword {
        get;
        set;
    }
}

Design View

Step 1

Create an action method in your controller as you want. Here I used the index action method.

Step 2

Right-click on the action method and click on Add View to add a new view.

Step 3

Return the model from the controller which you have created. If you want to pass some extra data you can pass it. Here as you see in the below code I just created object of model and pass that model to view.

public IActionResult Index() {
    QRCodeModel model = new QRCodeModel();
    return View(model);
}

Step 4

Design your view as per your requirements.

@model QRCodeModel
@{
    ViewData["Title"] = "Generate QR Code";
}

<form asp-action="Index">

    <div class="row mt-2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Select QR Code Type</label>
            <select asp-for="QRCodeType" id="QRCodeType" class="form-control" onchange="onQRCodeTypeChange()">
                <option value="1">Website</option>
                <option value="2">Bookmark URL</option>
                <option value="3">SMS</option>
                <option value="4">WhatsApp</option>
                <option value="5">Email</option>
                <option value="6">WIFI</option>
            </select>
        </div>
    </div>

    <!--  Website  -->
    <div class="row mt-2 hideDiv" id="DIV1">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Enter your website URL</label>
            <input autocomplete="off" type="url" asp-for="WebsiteURL" class="form-control" />
        </div>
    </div>

    <!-- Book Mark URL   -->
    <div class="row mt-2 hideDiv" id="DIV2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <label>Enter your URL</label>
            <input type="url" asp-for="BookmarkURL" class="form-control" autocomplete="off" />
        </div>
    </div>

    <!--  SMS  -->
    <div id="DIV3" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Phone Number with country code(eg. +91)</label>
                <input type="text" asp-for="SMSPhoneNumber" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter your Message</label>
                <textarea asp-for="SMSBody" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--  Whats App Message  -->
    <div id="DIV4" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WhatsApp Number with country code(eg. +91)</label>
                <input type="text" asp-for="WhatsAppNumber" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter your Message</label>
                <textarea asp-for="WhatsAppMessage" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--  Compose Email  -->
    <div id="DIV5" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Receive's Email Address</label>
                <input type="text" asp-for="ReceiverEmailAddress" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Email Subject</label>
                <input type="text" asp-for="EmailSubject" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter Email Message</label>
                <textarea asp-for="EmailMessage" class="form-control"></textarea>
            </div>
        </div>
    </div>

    <!--   WIFI   -->
    <div id="DIV6" class="hideDiv">
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WIFI Name</label>
                <input type="text" asp-for="WIFIName" class="form-control" autocomplete="off" />
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <label>Enter WIFI Password</label>
                <input type="text" asp-for="WIFIPassword" class="form-control" autocomplete="off" />
            </div>
        </div>
    </div>

    <div class="row mt-2">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <button type="submit" class="btn btn-primary">Generate</button>
            <button type="reset" class="btn btn-secondary">Reset</button>
        </div>
    </div>

    @if (!string.IsNullOrEmpty(Model.QRImageURL))
    {
        <div class="row mt-2" id="qrCodeImage">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <img height="250" width="250" src="@Model.QRImageURL" />
            </div>
        </div>
    }

</form>

@section Scripts{

    <script>
        $(document).ready(function () {
            $("#QRCodeType").trigger("change");
        });

        function onQRCodeTypeChange() {
            let qrcodeType = $("#QRCodeType").val();
            $(".hideDiv").hide();
            $("#DIV" + qrcodeType).show();
        }
    </script>
}

Code Explanation

As you can see in the above HTML code I created inputs as per my properties.

Here I add drop-down for QR Code type and based on that type I show and hide DIV of codes.

<div class="row mt-2">
  <div class="col-lg-6 col-md-6 col-sm-12">
    <label>Select QR Code Type</label>
    <select asp-for="QRCodeType" id="QRCodeType" class="form-control" onchange="onQRCodeTypeChange()">
      <option value="1">Website</option>
      <option value="2">Bookmark URL</option>
      <option value="3">SMS</option>
      <option value="4">WhatsApp</option>
      <option value="5">Email</option>
      <option value="6">WIFI</option>
    </select>
  </div>
</div>

For different types of QR Codes, I have created different div and gave an id to that div same as I gave the value in dropdown. Also gave same class name to all div.

At bottom, there are two buttons for submitting and resetting page.

Below button, there is an image that shows QR Code Image when the view return from controller after generating QR Code. Here we directly pass QR Code Image as base64 string instead of saving image and then show it on view side.

@if (!string.IsNullOrEmpty(Model.QRImageURL))
{
    <div class="row mt-2" id="qrCodeImage">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <img height="250" width="250" src="@Model.QRImageURL" />
        </div>
    </div>
}

At last, there is JavaScript code in the Scripts section which contain a function called onQRCodeTypeChange which gets value of QR Code Type drop-down then hide all the divs and only show which has id same as drop down value.

function onQRCodeTypeChange() {
    let qrcodeType = $("#QRCodeType").val();
    $(".hideDiv").hide();
    $("#DIV" + qrcodeType).show();
}

On the document ready event I triggered the change event of QR Code type drop-down.

$(document).ready(function() {
    $("#QRCodeType").trigger("change");
});

Code for Generate QR Code

Create post action method in your controller to post data from form. In this method, we are going to generate QR Code as per its type.

[HttpPost]
public IActionResult Index(QRCodeModel model) {
    Payload payload = null;
    switch (model.QRCodeType) {
        case 1: // website url
            payload = new Url(model.WebsiteURL);
            break;
        case 2: // bookmark url
            payload = new Bookmark(model.BookmarkURL, model.BookmarkURL);
            break;
        case 3: // compose sms
            payload = new SMS(model.SMSPhoneNumber, model.SMSBody);
            break;
        case 4: // compose whatsapp message
            payload = new WhatsAppMessage(model.WhatsAppNumber, model.WhatsAppMessage);
            break;
        case 5: //compose email
            payload = new Mail(model.ReceiverEmailAddress, model.EmailSubject, model.EmailMessage);
            break;
        case 6: // wifi qr code
            payload = new WiFi(model.WIFIName, model.WIFIPassword, WiFi.Authentication.WPA);
            break;
    }
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload);
    QRCode qrCode = new QRCode(qrCodeData);
    var qrCodeAsBitmap = qrCode.GetGraphic(20);
    // use this when you want to show your logo in middle of QR Code and change color of qr code
    //Bitmap logoImage = new Bitmap(@"wwwroot/img/Virat-Kohli.jpg");
    //var qrCodeAsBitmap = qrCode.GetGraphic(20, Color.Black, Color.Red, logoImage);
    string base64String = Convert.ToBase64String(BitmapToByteArray(qrCodeAsBitmap));
    model.QRImageURL = "data:image/png;base64," + base64String;
    return View("Index", model);
}
private byte[] BitmapToByteArray(Bitmap bitmap) {
    using(MemoryStream ms = new MemoryStream()) {
        bitmap.Save(ms, ImageFormat.Png);
        return ms.ToArray();
    }
}

Step 1

Create a new object of QRCodeGenerator class.

QRCodeGenerator qrGenerator = new QRCodeGenerator();

Step 2

Call the CreateQrCode method using this object and pass payload in its constructor. Payload is an object of PayloadGenerator.Payload type. There are different payload types as per QR Code types. We will discuss different types of payload later in this article.

QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload);

Step 3

Create object of QRCode type and Pass QR Data object to its constructor.

QRCode qrCode = new QRCode(qrCodeData);

Step 4

Call GetGraphic method of this QR Code object which take one integer parameter which define pixels per module.

var qrCodeAsBitmap = qrCode.GetGraphic(20);

There are also some overloaded methods using which you can change the color of QR Code and also set logo in QR Code.


// use this when you want to show your logo in middle of QR Code and change color of qr code
Bitmap logoImage = new Bitmap(@"wwwroot/img/Virat-Kohli.jpg");
var qrCodeAsBitmap = qrCode.GetGraphic(20, Color.Black, Color.Red, logoImage);

Step 5

GetGraphic method return bitmap image as return type. You can save this image in your local path but here I convert this bitmap image to byte array and then convert this byte array to base64 string which I’m going to bind in QRImageURL property and pass it to the view so user can view this QR Code.

string base64String = Convert.ToBase64String(BitmapToByteArray(qrCodeAsBitmap));
model.QRImageURL = "data:image/png;base64," + base64String;

For converting bitmap to byte first convert it to memory stream and then get byte array from this stream in user define method BitmapToByteArray. As you can see in below code.

private byte[] BitmapToByteArray(Bitmap bitmap) {
    using(MemoryStream ms = new MemoryStream()) {
        bitmap.Save(ms, ImageFormat.Png);
        return ms.ToArray();
    }
}

Step 6

Return view data after generating QR Code so user can see Generated QR Code in their browser.

Followings are different payload type which is used in this article.

Payload payload = null;

URL Payload

To generate QR Code that opens URL or any Website QRCoder provider payload type of URL class.

This class takes one argument in its constructor which is URL of website.

payload = new Url(model.WebsiteURL);

Bookmark Payload

To generate QR Code for bookmark type we have to Use Bookmark payload.

Bookmark class’s constructor takes two parameters first is the URL of the website and second is the title of the bookmark.

payload = new Bookmark(model.BookmarkURL, model.BookmarkURL);

SMS Payload

To generate QR Code for composing SMS we have to pass payload of SMS type. QR Code provider SMS class for this type of payload.

SMS class’s constructor takes two parameters first is phone number to whom you want to send the SMS and the second is the message you want to send. Message parameter is optional you can only pass phone number to it.

payload = new SMS(model.SMSPhoneNumber, model.SMSBody);

WhatsApp Message Payload

To generate QR Code that send WhatsApp message we have to pass WhatsAppMessage payload. QRCoder provides WhatsAppMessage class to generate payload.

WhatsAppMessage provides two overloaded methods one only takes one parameter which is message only and second takes two parameter WhatsApp number and message both.

payload = new WhatsAppMessage(model.WhatsAppNumber, model.WhatsAppMessage);

Mail Payload

To generate QR Code which compose email we have to use MAIL payload.

Mail class’s constructor does not required any parameter. It’s all parameters are by default set to null. But here we are going to pass receiver email address, Subject, and body of mail.

payload = new Mail(model.ReceiverEmailAddress, model.EmailSubject, model.EmailMessage);

WiFi Payload

To generate QR Code which connect to WIFI we have to pass data in WIFI payload.

WiFi class’s constructor takes three required parameter wifi name, wifi password, and authentication mode (WEP, WPA, nopass). You can pass any theme but mostly WPA is used in all wifi so here I by default set it.

payload = new WiFi(model.WIFIName, model.WIFIPassword, WiFi.Authentication.WPA);

Output Of URL QR Code

Generate QR Code in ASP.Net Core MVC 

Generate QR Code in ASP.Net Core MVC

Output Of SMS QR Code

Generate QR Code in ASP.Net Core MVC

Generate QR Code in ASP.Net Core MVC  Generate QR Code in ASP.Net Core MVC

Output Of WhatsApp Message QR Code

Generate QR Code in ASP.Net Core MVC

Generate QR Code in ASP.Net Core MVC

Output Of WIFI QR Code

Generate QR Code in ASP.Net Core MVC

Generate QR Code in ASP.Net Core MVC

Output Of Email QR Code

Generate QR Code in ASP.Net Core MVC

Generate QR Code in ASP.Net Core MVC  Generate QR Code in ASP.Net Core MVC

QR Code With Logo and Different Color

Generate QR Code in ASP.Net Core MVC

I hope you find this article helpful. You can download source code from my GitHub


Recommended Ebook

Dockerizing ASP.NET Core and Blazor Applications on Mac

Download Now!
Similar Articles