Our Customers
Contact Us Email: support@barcodelib.com
Home > .NET Barcode > How to barcode in C#? > How to generate barcode using C# in ASP.NET Core MVC web app?
Download Barcode for .NET Suite Trial

How to create barcodes in C#
ASP.NET Core MVC web app?

Detailed tutorial for rendering barcodes in ASP.NET Core Model-View-Controller (MVC) web app Using C# Code
How to create barcode using C# in ASP.NET Core MVC web app?

Requirements

In the following step by step tutorial, we'll show you how to quickly create a new ASP.NET Core MVC web app, and integrate online barcode generating feature on ASP.NET web page using C# codes.

1. Create a new ASP.NET Core Model-View-Controller (MVC) web app

Here we will quickly create a new ASP.NET Core web app using Visual Studio .NET
  • Start Visual Studio and select Create a new project
  • In the Create a new project dialog, select ASP.NET Core Web App (Model-View-Controller), and select button Next.
  • In the Configure your new project dialog, enter BarcodeLib.Create.ASPNETCoreMVCDemo for Project name. It is important to name the proejct BarcodeLib.Create.ASPNETCoreMVCDemo, including letter case, so the namespaces will match when you copy, paste the following C# example code.
  • Select button Create
  • In the Additional information diaplog, select .NET 6.0 or .NET 7.0 for the Framework dropdowns. Select button Create.
  • Now we have created a new ASP.NET Core MVC web project successfully, and we can find the build-in MVC views and controllers generated in the new ASP.NET Core project.

2. Install C# Barcode library and Nuget package

Now we will add BarcodeLib C# barcode generator library to the asp.net core project and also add a Nuget package named "System.Drawing.Common" from Microsoft.

Add C# Barcode DLL

  • In the Solution Explorer window, right click Dependencies, select Add Project Reference...
  • Select button Browse... in the Reference Manager dialog.
  • Choose dll file BarcodeLib.Barcode.Common.dll from BarcodeLib downloaded package /Dll/net-standard/
  • Check BarcodeLib.Barcode.Common.dll is selected, and select button OK


  • Now we have added the barcodelib barcode generator library dll. We will start to add a library "System.Drawing.Common" from Nuget


  • Install NuGet Package

  • Open Manage NuGet Packages... from Visual Studio
  • Enter System.Drawing.Common to search NuGet package
  • Select and install the System.Drawing.Common by Microsoft



  • Now we have installed the C# barcode library and nuget package successfully.


3. Add C# codes to MVC Controller

Here we add C# source codes to MVC controller HomeController.cs

using BarcodeLib.Barcode;
using BarcodeLib.Create.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
    {
        private static String tbData = "QR Code";
        private static String tbBarcodeWidth = "3";
        private static String tbResolution = "300";
        private static String tbBarColor = "000000";
        private static String tbBackgroundColor = "FFFFFF";

        public float BarcodeWebDisplayWidth { get; set; } = 0f;

        private readonly ILogger<HomeController> _logger;
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            ViewData["Data"] = tbData;
            ViewData["BarcodeWidth"] = tbBarcodeWidth;
            ViewData["Resolution"] = tbResolution;
            ViewData["BarColor"] = tbBarColor;
            ViewData["BackgroundColor"] = tbBackgroundColor;
            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> BarcodeRender()
        {
            try
            {
                tbData = Request.Form["tbData"].ToString();
                tbBarcodeWidth = Request.Form["tbBarcodeWidth"].ToString();
                tbResolution = Request.Form["tbResolution"].ToString();
                tbBarColor = Request.Form["tbBarColor"].ToString();
                tbBackgroundColor = Request.Form["tbBackgroundColor"].ToString();

                byte[] dataBytes = tryToCreateBarcode();
                if (dataBytes == null || dataBytes.Length == 0)
                    throw new Exception("Fail to encode QR Code");
                ViewData["BarcodeImage"] = System.Convert.ToBase64String(dataBytes);

                ViewData["BarcodeWebDisplayWidth"] = BarcodeWebDisplayWidth;

                ViewData["ViewResult"] = "Succeed";
                return Task.FromResult<IActionResult>(View());
            }
            catch (Exception)
            {
                ViewData["ViewResult"] = "Failed";
                return Task.FromResult<IActionResult>(View());
            }
        }

        private byte[] tryToCreateBarcode()
        {
            try
            {
                if (String.IsNullOrEmpty(tbData))
                    throw new Exception("QR Code data cannot be null or empty.");
                int imageDpi = Convert.ToInt32(tbResolution);
                if (imageDpi > 1000)
                    throw new Exception("QR Code image resolution is out of range.");
                float width = Convert.ToSingle(tbBarcodeWidth);
                if (width > 8F)
                    throw new Exception("QR Code width is out of range.");

                QRCode barcode = new QRCode();

                barcode.Data = tbData;

                barcode.UOM = UnitOfMeasure.INCH;

                barcode.ImageWidth = width;
                barcode.ImageHeight = width;

                BarcodeWebDisplayWidth = width * 96f;

                barcode.Resolution = imageDpi;

                barcode.ModuleColor = Color.FromArgb(
                    (byte)(HexToInt(tbBarColor[0]) * 16 + HexToInt(tbBarColor[1])),
                    (byte)(HexToInt(tbBarColor[2]) * 16 + HexToInt(tbBarColor[3])),
                    (byte)(HexToInt(tbBarColor[4]) * 16 + HexToInt(tbBarColor[5])));



                barcode.BackgroundColor = Color.FromArgb(
                    (byte)(HexToInt(tbBackgroundColor[0]) * 16 + HexToInt(tbBackgroundColor[1])),
                    (byte)(HexToInt(tbBackgroundColor[2]) * 16 + HexToInt(tbBackgroundColor[3])),
                    (byte)(HexToInt(tbBackgroundColor[4]) * 16 + HexToInt(tbBackgroundColor[5])));


                barcode.ImageFormat = ImageFormat.Png;

                return barcode.drawBarcodeAsBytes();
            }
            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;
        }
    }
}


4. Add C# codes to MVC Views

Here we add C# source codes to MVC view Index.cshtml from /Views/Home/

@{
    ViewData["Title"] = "ASP.NET Core MVC Barcode Generator Demo Page Powered by BarcodeLib C# Barcode Library";
}

<div class="text-center">
    <br />
    <form asp-action="BarcodeRender">
        <table align="center">
            <tbody>
                <tr>
                    <td align="right">QR Code data to encode: &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb1" name="tbData" style="width: 300px; " asp-for=@ViewData["Data"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Barcode Image Width (inch): &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb2" name="tbBarcodeWidth" style="width: 300px; " asp-for=@ViewData["BarcodeWidth"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Resolution (dpi): &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb3" name="tbResolution" style="width: 300px; " asp-for=@ViewData["Resolution"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Bar Module Color: &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb4" name="tbBarColor" style="width: 300px; " asp-for=@ViewData["BarColor"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Background Color: &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb5" name="tbBackgroundColor" style="width: 300px; " asp-for=@ViewData["BackgroundColor"] />
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
        <input type="submit" value="Render QR Code" />
        <br />
        <br />
    </form>
</div>
Add a new View BarcodeRender.cshtml to /Views/Home/ with the following contents

@{
    ViewData["Title"] = "Barcode Rendered";
}

<h1>QR Code Rendered - @ViewData["ViewResult"]</h1>

<div style="display:flex;justify-content:center">
    <a asp-action="Index">Back to Home</a>
</div>

<br />
<div style="display:flex;justify-content:center">
    <img src="data:image/png;base64,@ViewData["BarcodeImage"]" 
         width="@ViewData["BarcodeWebDisplayWidth"]"
         height="@ViewData["BarcodeWebDisplayWidth"]" />
</div>


5. Run the ASP.NET Core MVC web app

Now you have completed the ASP.NET Core MVC demo app, and it allows the web users to create and customize QR Code online in the ASP.NET MVC web app. Run the ASP.NET Core MVC web app directly from Visual Studio. You can generate QR Code 2d barcodes online in web browser.







Related Barcode Library Tutorials
Barcode for Visual C#.NET - Other Supported Barcodes
Linear / 1D Barcodes:
Matrix / 2D Barcodes: