How To Generate QR Code Using ASP.NET

Here, in this article, we will discuss how can we generate QRCode using ASP.NEt MVC 5. We will be using QRCoder library for this which is an open source library.

As the world is moving towards digital, QR code is very essential for any business to pay payments fast.

First of all, create a new project and install the QRCoder library by nuget.

qr-code-1

Now type the following command in the window.

Install-Package QRCoder -Version 1.3.5

Now it will download the package from nuget.

Now open View -> Home -> Index.cshtml and paste the following code in it.

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" name="codename"/>
        <input type="submit" value="Generate"/>
    }
    <hr/>
    @if (ViewBag.CodeImage != null)
    {
        <img src="@ViewBag.CodeImage" alt="" style="height:150px;width:150px"/>
    }
</body>
</html>

Now open the controller and paste the following code in it.

using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;

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

        [HttpPost]
        public ActionResult Index(string codename)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(codename, QRCodeGenerator.ECCLevel.Q);
                QRCode qrCode = new QRCode(qrCodeData);
                using (Bitmap bitMap = qrCode.GetGraphic(20))
                {
                    bitMap.Save(ms, ImageFormat.Png);
                    ViewBag.CodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
                }
            }
            return View();
        }
    }
}

Output:

output

You can download the source code from here

1 Comment

  1. Neelam

    Thank you So much

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories