In this article, we will see how to generate Barcode in the ASP.NET Core MVC project.
A Barcode is a computer-readable pattern of parallel vertical lines of varying thickness. It is like a unique fingerprint for a product and is often printed on the item itself or its packaging. Organizations – such as manufacturers, distributors, retailers, and blood banks – use barcoding to track and keep stock of goods.
Step 1 – Create and set up an Asp.net Core MVC Application.
You can give any name to this project. I will name it “MyBarCodeGenerator”.
I will remove all the Action Methods except Index Action Method from the HomeController, as I don’t need them for this example. My HomeController looks like the below:
Add Model class Response.cs, this model class will be used to send data from our controller to view.
public class Response { public string Data { get; set; } }
Step 2 – Edit Index View to Accept Input Data
Now, I will remove the existing code in the Index View of the Index Action Method. I will just add one input field to take the input data for generating the Barcode. And, an image tag that will display the QR code once generated. Below is the code for the Index View.
@model MyBarCodeGenerator.Models.Response @{ ViewData["Title"] = "Home Page"; } @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { <input type="text" name="inputData" /> <input type="submit" value="Generate Barcode" /> } <br /> @if (Model != null) { <img src="@Model.Data" /> }
Step 3 – Add BarcodeLib NuGet package
Step 4 – Add Post Action Method in HomeController
Now, I will add a post Action Method by name Index which will receive the input data and generate Barcode for us.
Below is the code for the post-action method for generating Barcode.
Add the below namespaces:
using BarcodeLib; using System.Drawing; using System.Drawing.Imaging;
[HttpPost] public IActionResult Index(string inputData) { MemoryStream memoryStream; using (memoryStream = new MemoryStream()) { Barcode barcode = new Barcode(); Image img = barcode.Encode(TYPE.CODE39, inputData, Color.Black, Color.White, 250, 100); img.Save(memoryStream, ImageFormat.Png); } Response response = new Response(); //Model response.Data = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray()); return View(response); }
Step 5 – Demo
Don’t forget to check out Generate QR Code in Asp.net Core with 4 Simple Steps
Wrapping Up
So this is how we generate Barcode in Asp.net core using the BarcodeLib Nuget Package. I hope, this blog post has helped you in learning and understanding how to generate Barcode in Asp.net Core. If you like it, share it with your friends and help this blog grow.