Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
In today's fast-paced digital landscape, the generation of QR codes has become an essential tool for efficient information sharing. These compact, two-dimensional barcodes, capable of storing a wide range of data, including URLs, text, contact information, product details, and much more, play a pivotal role in modern communication. Incorporating QR code generation capabilities into your ASP.NET MVC application allows you to empower users by seamlessly generating QR codes and enhancing their experience, streamlining interactions, and facilitating the effortless exchange of information.
If you're developing an ASP.NET MVC application and want to incorporate QR code generation capabilities, IronBarcode is an excellent library that simplifies the process. In this article, we will explore how to generate QR codes in ASP.NET MVC using the Iron Barcode library.
IronBarcode is a powerful and feature-rich QR Code generation and recognition library for .NET applications. With IronBarcode, developers can easily integrate barcode and QR Code functionality into their ASP.NET MVC projects, including the ability to generate QR codes. The library provides a comprehensive set of tools and APIs that simplify the process of creating and customizing QR codes, allowing developers to tailor them to their specific requirements.
IronBarcode offers extensive support for various barcode types, including QR codes, making it an ideal choice for projects that require QR code generation capabilities. It provides developers with the flexibility to specify the data to be encoded, control the size and resolution of the generated QR codes, and even add visual styling elements such as colors and logos. The library ensures high-quality barcode generation with precise control over every aspect of the QR code's appearance.
Beyond QR code generation, IronBarcode also includes robust features for barcode reading and decoding. It supports scanning and extracting data from QR codes, enabling applications to process information encoded within them. This functionality is beneficial for scenarios where barcode scanning and data extraction are necessary, such as inventory management, ticketing systems, and mobile applications.
Now, let's create a project to generate a QR code in the ASP.NET Core MVC Web app.
Before we delve into the implementation details, let's ensure that your ASP.NET MVC project is set up and ready to go. Whether you're starting a new project or working with an existing one, the steps outlined below will guide you through the process of integrating the Iron Barcode library into your application. In my case, I have created a new project.
Steps for creating a new project are as follows:
Visual Studio will then generate the project files and open the solution explorer, where you can see the project structure and start working on your code.
Now, we need to install Iron Barcode Library into our application.
To begin, open the Package Manager Console in Visual Studio and run the following command:
Install-Package IronBarCode
This command will install the Iron Barcode library and add the necessary references to your project.
Now, let's write some code to create QR codes.
QRCodeModel
Create a Model Class inside the Models folder and write the following code:
using System.ComponentModel.DataAnnotations;
public class QRCodeModel
{
[Display(Name = "Enter QR Code Text")]
public string QRCodeText { get; set; }
}
using System.ComponentModel.DataAnnotations;
public class QRCodeModel
{
[Display(Name = "Enter QR Code Text")]
public string QRCodeText { get; set; }
}
Imports System.ComponentModel.DataAnnotations
Public Class QRCodeModel
<Display(Name := "Enter QR Code Text")>
Public Property QRCodeText() As String
End Class
In your ASP.NET MVC project, create a new controller named QrCodeController
. To do this, right-click on the Controllers folder in your project's structure, select "Add," and then choose "Controller." From the available options, select "MVC Controller - Empty".
Write the following code in QrCodeController
:
using Microsoft.AspNetCore.Mvc;
using IronBarCode;
using System.IO;
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult CreateQRCode()
{
return View();
}
[HttpPost]
public IActionResult CreateQRCode(QRCodeModel generateQRCode)
{
try
{
// Creating QR Code
GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText);
string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(path, "qrcode.png");
barcode.SaveAsPng(filePath);
string fileName = Path.GetFileName(filePath);
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedQRCode/{fileName}";
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception ex)
{
// Handle exceptions
// Log the exception details here for troubleshooting and debugging.
throw;
}
return View();
}
}
using Microsoft.AspNetCore.Mvc;
using IronBarCode;
using System.IO;
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult CreateQRCode()
{
return View();
}
[HttpPost]
public IActionResult CreateQRCode(QRCodeModel generateQRCode)
{
try
{
// Creating QR Code
GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText);
string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(path, "qrcode.png");
barcode.SaveAsPng(filePath);
string fileName = Path.GetFileName(filePath);
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedQRCode/{fileName}";
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception ex)
{
// Handle exceptions
// Log the exception details here for troubleshooting and debugging.
throw;
}
return View();
}
}
Imports Microsoft.AspNetCore.Mvc
Imports IronBarCode
Imports System.IO
Public Class QrCodeController
Inherits Controller
Private ReadOnly _environment As IWebHostEnvironment
Public Sub New(ByVal environment As IWebHostEnvironment)
_environment = environment
End Sub
Public Function CreateQRCode() As IActionResult
Return View()
End Function
<HttpPost>
Public Function CreateQRCode(ByVal generateQRCode As QRCodeModel) As IActionResult
Try
' Creating QR Code
Dim barcode As GeneratedBarcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText)
Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedQRCode")
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
Dim filePath As String = System.IO.Path.Combine(path, "qrcode.png")
barcode.SaveAsPng(filePath)
Dim fileName As String = System.IO.Path.GetFileName(filePath)
Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}/GeneratedQRCode/{fileName}"
ViewBag.QrCodeUri = imageUrl
Catch ex As Exception
' Handle exceptions
' Log the exception details here for troubleshooting and debugging.
Throw
End Try
Return View()
End Function
End Class
This code sets up a controller that can generate QR codes. When the CreateQRCode
action is called, it takes the text for the QR code, generates the QR code image, saves it, and provides the URL for the image in the view for display. More detail is as follows:
IWebHostEnvironment
parameter to access the web hosting environment.CreateQRCode
action returns a view.CreateQRCode
action with the [HttpPost]
attribute takes a QRCodeModel
parameter, which contains the QR code text.QRCodeWriter
class from the Iron Barcode library.GeneratedQRCode
in the web root path.GeneratedQRCode
folder doesn't exist, it is created.ViewBag.QrCodeUri
property to be used in the view.CreateQRCode
ViewNow, to add a new view, right-click on the CreateQRCode
action method in the QrCodeController
class. Select "Add View," then select "Razor View," and click on the "Add" button.
A new window will appear as shown below.
Write the view name, select template "Create," and select our newly created model class QRCodeModel
. Click on Add Button. The view will be created. Replace your view with the below code.
@model QRCodeModel
@{
ViewData["Title"] = "CreateQRCode";
}
<h1>Create QRCode in ASP.NET MVC</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateQRCode">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="QRCodeText" class="control-label"></label>
<input asp-for="QRCodeText" class="form-control" />
<span asp-validation-for="QRCodeText" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
<div class="form-group">
@if (ViewBag.QrCodeUri != null)
{
<img src="@ViewBag.QrCodeUri" class="img-thumbnail" alt="Generated QR Code" />
}
</div>
</form>
</div>
</div>
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
Now, let's move to the Program.cs
class and change the default Controller Route.
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=CreateQRCode}/{id?}"
);
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=CreateQRCode}/{id?}"
);
app.MapControllerRoute(name:= "default", pattern:= "{controller=QrCode}/{action=CreateQRCode}/{id?}")
This will change the default route from HomeController
to our QrCodeController
.
Now, compile and run the project.
Enter text in the text box and click on the create button. A QR code will be created and displayed on the screen as shown below.
Now, let's add visual styling to our barcode by adding annotation text, QR Code value, and changing the QR Code color.
Add the following line of code inside the CreateQRCode
Action method.
barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF");
barcode.AddBarcodeValueTextBelowBarcode();
barcode.ChangeBackgroundColor(System.Drawing.Color.White);
barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed);
barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF");
barcode.AddBarcodeValueTextBelowBarcode();
barcode.ChangeBackgroundColor(System.Drawing.Color.White);
barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed);
barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF")
barcode.AddBarcodeValueTextBelowBarcode()
barcode.ChangeBackgroundColor(System.Drawing.Color.White)
barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed)
Now, run the project and generate the QR Code.
In ASP.NET MVC, integrating IronBarcode is straightforward. It provides a user-friendly interface, making it easy to work with QR codes. By leveraging IronBarcode, you can enhance your application by adding QR code functionality, enabling users to share and access information conveniently. IronBarcode is a valuable library that simplifies the process of generating QR codes and reading QR codes in ASP.NET MVC. It empowers developers to create dynamic applications that utilize the power of QR codes for efficient data sharing and retrieval.
Iron Barcode is free for personal use. However, for commercial purposes, you need to buy its commercial license, which comes with a free trial. You may also get a significant discount if you get the complete Iron Suite. Iron Suite is a comprehensive collection of .NET software components designed to simplify development tasks and enhance functionality. It offers five powerful libraries, including Iron Barcode, IronOCR, IronPDF, IronXL, and Iron Webscraper that enable developers to work with barcodes, optical character recognition, PDF processing, Excel, and CSV files seamlessly. You will get all five products for the price of two if you opt to purchase the complete Iron Suite.
IronBarcode is a powerful and feature-rich QR Code generation and recognition library for .NET applications, allowing developers to integrate barcode and QR Code functionality into their ASP.NET MVC projects.
To set up a new ASP.NET MVC project, open Microsoft Visual Studio, create a new project using the 'ASP.NET Core web app (Model-view-controller)' template, and install the IronBarcode library via the Package Manager Console using the command: Install-Package IronBarCode.
To generate a QR code, create a QRCodeModel to capture input, set up a controller action to generate and save the QR code using IronBarcode's QRCodeWriter class, and display the generated QR code on a view.
IronBarcode allows customization such as specifying the data to be encoded, controlling size and resolution, adding visual styling elements like colors and logos, and adding annotation text above or below the barcode.
After generating a QR code, store its URL in the ViewBag and use an HTML image tag in your Razor view to display the image using the stored URL.
Yes, IronBarcode includes robust features for barcode reading and decoding, supporting scanning and extracting data from QR codes, useful for tasks like inventory management and ticketing systems.
IronBarcode is free for personal use. For commercial purposes, a commercial license is required, which is available for purchase and comes with a free trial.
The Iron Suite is a comprehensive collection of .NET software components, offering libraries like Iron Barcode, Iron OCR, Iron PDF, Iron XL, and Iron Webscraper, providing tools for barcode, OCR, PDF, Excel, and web scraping functionalities.
To change the default route, modify the 'MapControllerRoute' method in the 'Program.cs' file to set the desired controller and action as the default.
Common use cases for QR codes include inventory management, quick access to websites, contactless payment systems, ticketing, and mobile applications where rapid information exchange is required.