C# Barcode Generator > How to create barcode in C#? > How to generate, print barcode using C# in ASP.NET Core MVC web app?

How to generate barcode in C# ASP.NET Core MVC web app?

Detailed step by step tutorial for print barcode in ASP.NET Core Model-View-Controller (MVC) web app Using C# Code

C# Barcode Generator Library

QR Code, Data Matrix, Code 128, GS1, EAN/UPC. Unicode text encoding supported.

Download Now
NuGet Ready
.NET 5+
.NET Framework 4.x, 3.x, 2.x




How to create QR Code 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.BarcodeGenerator.AspNetCore.MVC.Demo for Project name. It is important to name the proejct BarcodeLib.BarcodeGenerator.AspNetCore.MVC.Demo, 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 8.0 (Long Term Support) 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.BarcodeGenerator.AspNetCore.MVC.Demo.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Drawing;

namespace BarcodeLib.BarcodeGenerator.AspNetCore.MVC.Demo.Controllers
{
    public class HomeController : Controller
    {
        private static String tbData = "Code 128";
        private static String tbBarcodeWidth = "3";
        private static String tbBarcodeHeight = "1.6";
        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["BarcodeHeight"] = tbBarcodeHeight;
            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> BarcodeViewer()
        {
            try
            {
                tbData = Request.Form["tbData"].ToString();
                tbBarcodeWidth = Request.Form["tbBarcodeWidth"].ToString();
                tbBarcodeHeight = Request.Form["tbBarcodeHeight"].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 barcode");
                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("Barcode data cannot be null or empty.");
                int imageDpi = Convert.ToInt32(tbResolution);
                if (imageDpi > 1000)
                    throw new Exception("Barcode image resolution is out of range.");
                float width = Convert.ToSingle(tbBarcodeWidth);
                if (width > 8F)
                    throw new Exception("Barcode width is out of range.");

                float height = Convert.ToSingle(tbBarcodeHeight);
                if (width > 4F)
                    throw new Exception("Barcode height is out of range.");

                Linear barcode = new Linear();
                barcode.Type = BarcodeType.CODE128;
                barcode.Data = tbData;

                barcode.UOM = UnitOfMeasure.INCH;

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

                BarcodeWebDisplayWidth = width * 96f;

                barcode.Resolution = imageDpi;

                barcode.BarColor = 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 = BLImageFormat.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 by BarcodeLib C# Barcode Library";
}

<div class="text-center">
    <br />
    <form asp-action="BarcodeViewer">
        <table align="center">
            <tbody>
                <tr>
                    <td align="right">Barcode 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">Barcode Image Height (inch): &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb6" name="tbBarcodeHeight" style="width: 300px; " 
                            asp-for=@ViewData["BarcodeHeight"] />
                    </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="Print Barcode" />
        <br />
        <br />
    </form>
</div>
Add a new View BarcodeViewer.cshtml to /Views/Home/ with the following contents

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

<h1>Barcode Viewer - @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["BarcodeWebDisplayHeight"]" />
</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 barcode online in the ASP.NET MVC web app. Run the ASP.NET Core MVC web app directly from Visual Studio. You can generate Code 128 barcodes online in web browser.







Related Barcode Library Tutorials