In this article I will explain with an example, how to dynamically generate and display QR Code Image in ASP.Net MVC Razor.
The QR Code Image will be dynamically generated in ASP.Net MVC Razor using the QRCoder library which is an Open Source Library QR code generator.
QRCoder Library
You will need to download the QRCoder library from the following location and open the project in Visual Studio and build it. Once it is build, you can find the DLL in the Debug folder.
Note: You can also find the QRCoder DLL in the attached sample project.
You will need to import the following namespaces.
using QRCoder;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside this Action method, the value of the QR Code entered in the TextBox is captured as parameter.
The QR Code is passed to the CreateQrCode method of the QRCoder library which returns a Bitmap image.
Finally the Bitmap image is saved to MemoryStream and then converted to Base64 string.
The Base64 string is set into a ViewBag object.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        return View();
    public ActionResult Index(string qrcode)
        using (MemoryStream ms = new MemoryStream())
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(qrcode, QRCodeGenerator.ECCLevel.Q);
            using (Bitmap bitMap = qrCode.GetGraphic(20))
                bitMap.Save(ms, ImageFormat.Png);
                ViewBag.QRCodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
        return View();
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – 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 TextBox, a Submit Button and an Image element.
When the Submit Button is clicked, the Form is submitted and the generated QR Code Image is displayed in HTML Image element using ViewBag object.
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        <input type="text" name="qrcode"/>
        <input type="submit" value="Generate"/>
    @if (ViewBag.QRCodeImage != null)
        <img src="@ViewBag.QRCodeImage" alt="" style="height:150px;width:150px"/>
ASP.Net MVC: Dynamically generate and display QR Code Image