In this article I will explain with an example, how to dynamically generate and display
QRCode Image in ASP.Net Core (.Net Core 8) MVC.
Installing QRCoder package and System.Drawing.Common using Nuget
Namespaces
You will need to import the following namespaces.
using QRCoder;
using System.Drawing;
using System.Drawing.Imaging;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method accepts the value entered in the TextBox as parameter.
Inside this Action method, an object of QRCodeGenerator is created and QRCode class object is initialized with calling CreateQrCode method of QRCodeGenerator class which accepts the TextBox value as parameter.
The CreateQrCode method returns the Bitmap image which is saved to the MemoryStream and converted to BASE64 string.
Finally, the BASE64 string is set into
ViewBag object.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string qrcode)
{
using (MemoryStream ms = new MemoryStream())
{
//Generate QRCode object.
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCode qrCode = new QRCode(qrGenerator.CreateQrCode(qrcode, QRCodeGenerator.ECCLevel.Q));
//Create a Bitmap using the QRCode.
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
bitMap.Save(ms, ImageFormat.Png);
ViewBag.QRCodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
}
return View();
}
}
View
HTML Markup
The View consists of an HTML Form created with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View consists of an HTML INPUT TextBox, a Submit Button and an Image element.
Submitting the Form
When the
Submit Button is clicked, the
ViewBag object is checked for NULL and if it is not NULL then the value of the
ViewBag is set to the
src property of the Image element and the QRCode is displayed.
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body {font-family:Arial; font-size:10pt; }
</style>
</head>
<body>
<form asp-action="Index" asp-controller="Home">
<input type="text" name="qrcode" />
<input type="submit" value="Generate" />
</form>
@if (ViewBag.QRCodeImage != null)
{
<img src="@ViewBag.QRCodeImage" alt="" style="height:150px;width:150px" />
}
</body>
</html>
Screenshot
Demo
Downloads