- Detailed steps explain how to create QR Code 2d barcodes in web browser in a new ASP.NET Core MVC web app using C# codes.
- Easy to customize the tutorial to create other barcodes, such as Data Matrix, PDF417 2d barcodes in C# application, also create Code 39, Code 128, EAN-13, UPC-A 20+ linear barcodes in C# .NET projects
- Compatible with GS1 System, easy to encode GS1 data message into GS1-128, GS1 QR Code and Data Matrix
- Easy to customize the generated barcode with colors, barcode dimension width and height, 1d barcode text styles.
- Support both System.Drawing.Common for Windows development and SkiaSharp for Linux, MacOS, non-Windows development
- Fully support .NET 8, 7, 6, 5, .NET Core 3.x, 2.x ASP.NET Core MVC web apps
- High quality C#.NET barcode generator library to print high resolution dpi barcode image for all scanners and printers
Tutorial: How to create barcode in ASP.NET Core MVC web pages using C#?
Step 1: Create a new ASP.NET Core MVC web app project
1.1: Open Visual Studio 2022, choose project template as
ASP.NET Core Web App (Model-View-Controller), and click button "Next".
Input "Project name" as
KeepAutomation.BarcodeGenerator.ASPNETCoreMVCDemo, and click button "Next".
Select
.NET 6.0 (Long-term support), and then click button "Create".
Now, a new ASP.NET Core MVC web app has been created successfully. We will install the barcode generator dll library and required NuGet package to the ASP.NET MVC web app.
Step 2: Install Barcode Generator dll and Nuget pacakge
In Visual Studio Solution Explorer window, right click Dependecies, and choose pupup menu
Add Project Reference....
Click button
Browse... to select the KeepAutomation .NET Barcode Generator dll
Navigate to folder
/DLL/NetStandard/ from the downloaded package, and select dll file
KeepAutomation.Barcode.Standard.dll
You can find that the selected KeepAutomation barcode library has been added to the reference manager. Click button "OK" to add the library to the MVC app.
Now you have added the barcode generator ASP.NET library to your MVC C# project successfully.
Again in Visual Studio Solution Explorer window, right click Dependecies, and choose pupup menu
Manage NuGet Packages....
Search
System.Drawing.Common from the NuGet Package Manager. And install it.
Now we have installed the KeepAutomation barcode generator ASP.NET library and required NuGet packages to the ASP.NET MVC app successfully.
Step 3: Add C# codes to MVC app Controller and View
Now we will add C# source codes to enable online QR Code barcode generating in web browser. To do it, we will
modify an existing MVC controller and view, and create a new view in the newly created ASP.NET Core MVC web app.
Replace the file
HomeController.cs with the following C# source codes:
using KeepAutomation.Barcode.Bean;
using KeepAutomation.BarcodeGenerator.ASPNETCoreMVCDemo.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
namespace OnBarcode.QRCodeGenerator.ASPNETCoreMVCDemo.Controllers
{
public class HomeController : Controller
{
// QR Code data to encode
private static String tbCode2Encode = "QR Code";
// QR Code barcode image width and height.
// Must be a positive float value less than 8.
private static String tbBarcodeWidth = "3";
// Barcode Image resolution in DPI
// Must be a positive int value less than 1000.
private static String tbDpi = "300";
// Hex String: from 0 to FFFFFF
private static String tbBarcodeForeColor = "000000";
// Hex String: from 0 to FFFFFF
private static String tbBarcodeBackColor = "FFFFFF";
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
// Set default values
ViewData["Code2Encode"] = tbCode2Encode;
ViewData["BarcodeWidth"] = tbBarcodeWidth;
ViewData["Dpi"] = tbDpi;
ViewData["ForeColor"] = tbBarcodeForeColor;
ViewData["BackColor"] = tbBarcodeBackColor;
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
//
public Task<IActionResult> BarcodeGenerator()
{
try
{
// Update backup
tbCode2Encode = Request.Form["tbCode2Encode"].ToString();
tbBarcodeWidth = Request.Form["tbBarcodeWidth"].ToString();
tbDpi = Request.Form["tbDpi"].ToString();
tbBarcodeForeColor = Request.Form["tbForeColor"].ToString();
tbBarcodeBackColor = Request.Form["tbBackColor"].ToString();
byte[] dataBytes = tryToCreateBarcode();
if (dataBytes == null || dataBytes.Length == 0)
throw new Exception("Fail to create barcode");
ViewData["BarcodeImage"] = System.Convert.ToBase64String(dataBytes);
ViewData["ViewResult"] = "Succeed";
return Task.FromResult<IActionResult>(View());
}
catch (Exception)
{
ViewData["ViewResult"] = "Failed";
return Task.FromResult<IActionResult>(View());
}
}
// Create barcode. Return empty array if failed.
private byte[] tryToCreateBarcode()
{
try
{
if (String.IsNullOrEmpty(tbCode2Encode))
throw new Exception("Message cannot be null or empty.");
int imageDpi = Convert.ToInt32(tbDpi);
if (imageDpi > 1000)
throw new Exception("Barcode image DPI resolution is out of range.");
float width = Convert.ToSingle(tbBarcodeWidth);
if (width > 8F)
throw new Exception("Barcode dimension width is out of range.");
BarCode aBarcode = new BarCode();
aBarcode.Symbology = KeepAutomation.Barcode.Symbology.QRCode;
aBarcode.CodeToEncode = tbCode2Encode;
aBarcode.QRCodeDataMode = KeepAutomation.Barcode.QRCodeDataMode.Auto;
aBarcode.AutoSizeAdjust = true;
aBarcode.BarcodeUnit = KeepAutomation.Barcode.BarcodeUnit.Inch;
aBarcode.BarCodeWidth = width;
aBarcode.BarCodeHeight = width;
aBarcode.DPI = imageDpi;
aBarcode.ForeColor = Color.FromArgb(
(byte)(HexToInt(tbBarcodeForeColor[0]) * 16 + HexToInt(tbBarcodeForeColor[1])),
(byte)(HexToInt(tbBarcodeForeColor[2]) * 16 + HexToInt(tbBarcodeForeColor[3])),
(byte)(HexToInt(tbBarcodeForeColor[4]) * 16 + HexToInt(tbBarcodeForeColor[5])));
aBarcode.BackColor = Color.FromArgb(
(byte)(HexToInt(tbBarcodeBackColor[0]) * 16 + HexToInt(tbBarcodeBackColor[1])),
(byte)(HexToInt(tbBarcodeBackColor[2]) * 16 + HexToInt(tbBarcodeBackColor[3])),
(byte)(HexToInt(tbBarcodeBackColor[4]) * 16 + HexToInt(tbBarcodeBackColor[5])));
aBarcode.ImageFormat = ImageFormat.Png;
return aBarcode.generateBarcodeToByteArray();
}
catch (Exception)
{
return new byte[0];
}
}
public static int HexToInt(char c)
{
if (c >= '0' && c <= '9')
return (int)c - (int)'0';
if (c >= 'A' && c <= 'F')
return (int)c - (int)'A' + 10;
if (c >= 'a' && c <= 'f')
return (int)c - (int)'a' + 10;
return 0;
}
}
}
Replace the file
Index.cshtml with the following C# codes:
@{
ViewData["Title"] = "KeepAutomation ASP.NET Core MVC Barcode Generator Demo Page";
}
<div class="text-center">
<br />
<form asp-action="BarcodeGenerator">
<table align="center">
<tbody>
<tr>
<td align="right">QR Code data to encode: </td>
<td>
<input type="text" id="tb1" name="tbCode2Encode" style="width: 300px; " asp-for=@ViewData["Code2Encode"] />
</td>
</tr>
<tr>
<td align="right">Barcode Image Width (inch): </td>
<td>
<input type="text" id="tb2" name="tbBarcodeWidth" style="width: 300px; " asp-for=@ViewData["BarcodeWidth"] />
</td>
</tr>
<tr>
<td align="right">Resolution (dpi): </td>
<td>
<input type="text" id="tb3" name="tbDpi" style="width: 300px; " asp-for=@ViewData["Dpi"] />
</td>
</tr>
<tr>
<td align="right">Fore Color: </td>
<td>
<input type="text" id="tb4" name="tbForeColor" style="width: 300px; " asp-for=@ViewData["ForeColor"] />
</td>
</tr>
<tr>
<td align="right">Back Color: </td>
<td>
<input type="text" id="tb5" name="tbBackColor" style="width: 300px; " asp-for=@ViewData["BackColor"] />
</td>
</tr>
</tbody>
</table>
<br />
<input type="submit" value="Create Barcode" />
<br />
<br />
</form>
</div>
Create a new View
BarcodeGenerator.cshtml under
/Views/Home
Replace the file content with the following C# source code
@{
ViewData["Title"] = "Barcode Generator";
}
<h1>Create Barcode - @ViewData["ViewResult"]</h1>
<div style="display:flex;justify-content:center">
<a asp-action="Index">Back to Index</a>
</div>
<br />
<div style="display:flex;justify-content:center">
<img src="data:image/png;base64,@ViewData["BarcodeImage"]" />
</div>
Step 4: Run the ASP.NET Core MVC web app to create QR Code barcodes online in the web browser
Now you can run the ASP.NET Core MVC web app from Visual Studio, and generate QR Code online in the web browser
Change the QR Code settings, and click button
Create Barcode. You will view the generated QR Code online in the web browser.