Click here to Skip to main content
15,350,990 members
Articles / Web Development / ASP.NET
Posted 25 Mar 2014

Tagged as


34 bookmarked

Generate Bar Code Using ASP.NET MVC 4

Rate me:
Please Sign up or sign in to vote.
4.92/5 (13 votes)
25 Mar 2014CPOL2 min read
This tip introduces approaches to generate bar code in ASP.NET MVC project.


Bar code is a machine-readable code in the form of numbers and a pattern of parallel lines of varying widths, printed on a commodity and used especially for stock control. This tip introduces approaches to generate bar code in ASP.NET MVC project. Bar code has a unique pattern of parallel lines; this pattern represent a unique number. Using this number, we get information of product that has this bar code.

To start this task, you need a Font name "FREE3OF9.TTF" (Code 39 Font). You can download it from here. Click on Download the Code 39 font package.

Using the Code

First of all, we create a database table for storing, barcode image or barcode number that is used for display bar code. Design of table is as follows. In the database table, we store bar code image as binary string.

Image 1

Now, we create model in model folder for data accessing. Add the following code in model.

namespace BarCode.Models
    public class BarCodeModel
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public byte[] BarcodeImage { get; set; }
        public string Barcode { get; set; }
        public string ImageUrl { get; set; }

Now open Visual Studio 2012. After that, select new project and click on ASP.NET MVC4 Web Application in Visual C#. Name the project BarCode and whatever you like. Create a controller named HomeController and in this controller, create an ActionResult method named Index.

public ActionResult Index()
  return View();

Now create a view, right click on the Index action method and select Add View and then click OK. Write the following code in this view for create insert form using @html helper or create strongly typed view.

@model BarCode.Models.BarCodeModel
    ViewBag.Title = "Index";
@using (Html.BeginForm())
        <legend>Add Product</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
            <input type="submit" value="Create" />
    @Html.ActionLink("Back to List", "Index")

For generating bar code, we are adding two classes, the first is "barcodecs" and the other is "BarCode39". Barcodecs class has two methods, the first is "generateBarcode" which is used for generating unique bar code number and the other method is "getBarcodeImage" which is used for creating bar code image using "Code 39 Font".

"barcode39.cs" code is available in the given source code file. barcodecs.cs code is as follows:

namespace BarCode.Models
    public class barcodecs
        public string generateBarcode()
                string[] charPool = "1-2-3-4-5-6-7-8-9-0".Split('-');
                StringBuilder rs = new StringBuilder();
                int length = 6;
                Random rnd = new Random();
                while (length-- > 0)
                    int index = (int)(rnd.NextDouble() * charPool.Length);
                    if (charPool[index] != "-")
                        charPool[index] = "-";
                return rs.ToString();
            catch (Exception ex)
                //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);
            return "";
        public Byte[] getBarcodeImage(string barcode, string file)
                BarCode39 _barcode = new BarCode39();
                int barSize = 16;
                string fontFile = HttpContext.Current.Server.MapPath("~/fonts/FREE3OF9.TTF");
                return (_barcode.Code39(barcode, barSize, true, file, fontFile));
            catch (Exception ex)
                //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);
            return null;

Now, create HttpPost Action method for getting posted data. I am using "linq to sql"(dbml file) for data insert data in table.

Now, create a data context for making a connection to database:

ProductDataContext context = new ProductDataContext(); 

Now, create an object of product table for inserting data in table and write the following code to action method. Here, barcode is a unique number that is generated by generateBarcode() method and barcode image is byte code of image that is generated by getBarCodeImage(). The method of barcodecs.cs is as follows:

        public ActionResult Index(BarCodeModel model)
            barcodecs objbar = new barcodecs();
            Product objprod = new Product()
                Name = model.Name,
                Description = model.Description,
                Barcode = objbar.generateBarcode(),
                BarCodeImage =   objbar.getBarcodeImage(objbar.generateBarcode(), model.Name)
            return RedirectToAction("BarCode", "Home");

Now, create another action method for displaying barcode. In this action method, we get data from database. The code is as given below:

public ActionResult BarCode()
            SqlConnection con = new SqlConnection(
                "Data Source=;Initial Catalog=Hospital;
                Persist Security Info=True;User ID=sa;Password=MORarka#1234");
            string query = "select * From Product";
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(query, con);
            IList<BarCodeModel> model = new List<BarCodeModel>();
            for (int i = 0; i < dt.Rows.Count; i++)
                var p = dt.Rows[i]["BarCodeImage"];
                model.Add(new BarCodeModel()
                    Name = dt.Rows[i]["Name"].ToString(),
                    Description = dt.Rows[i]["Description"].ToString(),
                    Barcode = dt.Rows[i]["Barcode"].ToString(),
                    ImageUrl = dt.Rows[i]["BarCodeImage"] != null ? "data:image/jpg;base64," + 
                        Convert.ToBase64String((byte[])dt.Rows[i]["BarCodeImage"]) : ""

            return View(model);

Now, right click on BarCode() action method and add a new view for displaying barcode. Write the following code on BarCode.cshtml for displaying data.

@model IEnumerable<BarCode.Models.BarCodeModel>
    ViewBag.Title = "BarCode";
    @Html.ActionLink("Create New", "Create")
            @Html.DisplayNameFor(model => model.Name)
            @Html.DisplayNameFor(model => model.Description)
            @Html.DisplayNameFor(model => model.Barcode)
            @Html.DisplayNameFor(model => model.ImageUrl)
@foreach (var item in Model) {
            @Html.DisplayFor(modelItem => item.Name)
            @Html.DisplayFor(modelItem => item.Description)
            @Html.DisplayFor(modelItem => item.Barcode)
           <img src="@item.ImageUrl"/>

Now, build and run your application.

Image 2

Insert and submit data in the form if data successfully inserted, then your bar code is generated and it looks like:

Image 3

Your bar code is successfully generated. If you have any queries, then feel free to contact me.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Yogesh Kumar Tyagi
Software Developer Pure Diets India Limited
India India
No Biography provided

Comments and Discussions

QuestionBarcode cannot read again Pin
Member 1303519714-Oct-20 23:00
MemberMember 1303519714-Oct-20 23:00 
QuestionBarcode not working on barcode scanner Pin
Member 111123576-Jan-19 15:18
MemberMember 111123576-Jan-19 15:18 
Good day to you sir. I tried your code and it's working fine. but, why i can't read the generated barcode on my barcode scanner device? barcode scanner brand "YOUJIE"
QuestionNot able to scan Pin
Member 1229202524-Jan-18 5:04
MemberMember 1229202524-Jan-18 5:04 
AnswerRe: Not able to scan Pin
Yogesh Kumar Tyagi9-Mar-18 0:54
professionalYogesh Kumar Tyagi9-Mar-18 0:54 
GeneralRe: Not able to scan Pin
Member 111123576-Jan-19 15:22
MemberMember 111123576-Jan-19 15:22 
QuestionCode is working just need some modification on it. Pin
Pawandeep Kushwaha20-Jan-18 8:30
MemberPawandeep Kushwaha20-Jan-18 8:30 
AnswerRe: Code is working just need some modification on it. Pin
Yogesh Kumar Tyagi22-Jan-18 3:18
professionalYogesh Kumar Tyagi22-Jan-18 3:18 
GeneralRe: Code is working just need some modification on it. Pin
Pawandeep Kushwaha22-Jan-18 3:34
MemberPawandeep Kushwaha22-Jan-18 3:34 
AnswerRe: Code is working just need some modification on it. Pin
Member 1229202524-Jan-18 5:06
MemberMember 1229202524-Jan-18 5:06 
Member 1162099713-Dec-17 19:59
MemberMember 1162099713-Dec-17 19:59 
Yogesh Kumar Tyagi22-Jan-18 3:20
professionalYogesh Kumar Tyagi22-Jan-18 3:20 
QuestionHow to scan this generated barcode Pin
Member 133899145-Dec-17 3:04
MemberMember 133899145-Dec-17 3:04 
QuestionGood but would be better if i could also convert string Pin
Member 127709156-Nov-17 22:03
MemberMember 127709156-Nov-17 22:03 
AnswerRe: Good but would be better if i could also convert string Pin
Yogesh Kumar Tyagi22-Jan-18 3:23
professionalYogesh Kumar Tyagi22-Jan-18 3:23 
Generalthe barcode can be scan with scanner if asterisk is added in front and back of the barcode ( * + barcode + * ) Pin
Clarie Tan20-Apr-17 16:56
MemberClarie Tan20-Apr-17 16:56 
QuestionRegarding barcode scanning Pin
Naveenaju27-Nov-16 20:51
professionalNaveenaju27-Nov-16 20:51 
QuestionHow to read the barcode with scanner Pin
Member 117103686-Nov-16 22:35
MemberMember 117103686-Nov-16 22:35 
QuestionNot Generate Barcode when Pass String Pin
Member 1130133820-Aug-16 21:28
MemberMember 1130133820-Aug-16 21:28 
QuestionFixing BarCode Size Width height Pin
Member 1258210214-Jun-16 21:36
MemberMember 1258210214-Jun-16 21:36 
AnswerRe: Fixing BarCode Size Width height Pin
Yogesh Kumar Tyagi22-Jun-16 4:24
professionalYogesh Kumar Tyagi22-Jun-16 4:24 
QuestionProblem in generating barcode image Pin
Member 1257640410-Jun-16 0:22
MemberMember 1257640410-Jun-16 0:22 
AnswerRe: Problem in generating barcode image Pin
Yogesh Kumar Tyagi22-Jun-16 4:25
professionalYogesh Kumar Tyagi22-Jun-16 4:25 
GeneralRe: Problem in generating barcode image Pin
KapZs7-Nov-16 0:32
MemberKapZs7-Nov-16 0:32 
GeneralRe: Problem in generating barcode image Pin
Yogesh Kumar Tyagi7-Nov-16 2:01
professionalYogesh Kumar Tyagi7-Nov-16 2:01 
GeneralRe: Problem in generating barcode image Pin
KapZs9-Nov-16 21:54
MemberKapZs9-Nov-16 21:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.