Click here to Skip to main content
12,297,275 members (64,555 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

25.6K views
2K downloads
31 bookmarked
Posted

Generate Bar Code Using ASP.NET MVC 4

, 25 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This tip introduces approaches to generate bar code in ASP.NET MVC project.

Introduction

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.

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";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Add Product</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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()
        {
            try
            {
                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] != "-")
                    {
                        rs.Append(charPool[index]);
                        charPool[index] = "-";
                    }
                    else
                        length++;
                }
                return rs.ToString();
            }
            catch (Exception ex)
            {
                //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);
            }
            return "";
        }
 
        public Byte[] getBarcodeImage(string barcode, string file)
        {
            try
            {
                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:

[HttpPost]
        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)
            };
            context.Products.InsertOnSubmit(objprod);
            context.SubmitChanges();
            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=192.168.137.1;Initial Catalog=Hospital;
                Persist Security Info=True;User ID=sa;Password=MORarka#1234");
            string query = "select * From Product";
            DataTable dt = new DataTable();
            con.Open();
            SqlDataAdapter sda = new SqlDataAdapter(query, con);
            sda.Fill(dt);
            con.Close();
            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";
}
 
<h2>BarCode</h2>
 
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Barcode)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ImageUrl)
        </th>
        <th></th>
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Barcode)
        </td>
        <td>
           <img src="@item.ImageUrl"/>
        </td>
       
    </tr>
}
 
</table>

Now, build and run your application.

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

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

License

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

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
Questiondoesn't scan with barcode reader Pin
MLightsOut11-Apr-16 10:33
memberMLightsOut11-Apr-16 10:33 
QuestionSave the barcode to pdf file Pin
cristiamz25-Mar-16 19:14
membercristiamz25-Mar-16 19:14 
Questiongood Pin
nguyen cuongdf3-Mar-16 16:49
membernguyen cuongdf3-Mar-16 16:49 
QuestionUnable to create image after creating Product table in SQL Express, and point to local host in web.config Pin
Ron Yam9-Feb-16 8:36
memberRon Yam9-Feb-16 8:36 
AnswerRe: Unable to create image after creating Product table in SQL Express, and point to local host in web.config Pin
Yogesh Kumar Tyagi17-Feb-16 1:30
professionalYogesh Kumar Tyagi17-Feb-16 1:30 
Question[My vote of 1] you kill my time Pin
Hossein Safdari30-Oct-15 9:02
memberHossein Safdari30-Oct-15 9:02 
Questionyou kill my time Pin
Hossein Safdari30-Oct-15 9:02
memberHossein Safdari30-Oct-15 9:02 
Questiongive Invalid column name 'BarCodeImage'. error recive Pin
Ali_Eagle23-Aug-15 23:28
memberAli_Eagle23-Aug-15 23:28 
QuestionGenerated Bar Code doesn't scan Pin
Divyans Mahansaria28-Feb-15 23:29
professionalDivyans Mahansaria28-Feb-15 23:29 
Questionthanks for sharing. Pin
kavnico9-Nov-14 19:09
memberkavnico9-Nov-14 19:09 
AnswerRe: thanks for sharing. Pin
Yogesh Kumar Tyagi9-Nov-14 19:24
professionalYogesh Kumar Tyagi9-Nov-14 19:24 
Questionneed a help on class barcode39 Pin
sheelakr27-Oct-14 21:03
membersheelakr27-Oct-14 21:03 
AnswerRe: need a help on class barcode39 Pin
Yogesh Kumar Tyagi28-Oct-14 18:40
professionalYogesh Kumar Tyagi28-Oct-14 18:40 
QuestionMessage Automatically Removed Pin
8-Oct-14 22:44
memberpaul00098-Oct-14 22:44 
AnswerRe: Ask Pin
Yogesh Kumar Tyagi9-Oct-14 18:49
professionalYogesh Kumar Tyagi9-Oct-14 18:49 
AnswerSolution to read codebar Pin
Member 1043982019-Aug-14 7:16
memberMember 1043982019-Aug-14 7:16 
GeneralRe: Solution to read codebar Pin
Yogesh Kumar Tyagi19-Aug-14 18:37
professionalYogesh Kumar Tyagi19-Aug-14 18:37 
QuestionNeed help Pin
Member 1018659110-Aug-14 5:14
memberMember 1018659110-Aug-14 5:14 
AnswerRe: Need help Pin
Yogesh Kumar Tyagi10-Aug-14 18:19
professionalYogesh Kumar Tyagi10-Aug-14 18:19 
GeneralRe: Need help Pin
Member 1018659111-Aug-14 8:06
memberMember 1018659111-Aug-14 8:06 
SuggestionRe: Need help Pin
Member 1043982019-Aug-14 11:25
memberMember 1043982019-Aug-14 11:25 
GeneralRe: Need help Pin
Yogesh Kumar Tyagi19-Aug-14 18:35
professionalYogesh Kumar Tyagi19-Aug-14 18:35 
GeneralRe: Need help Pin
Member 1043982020-Aug-14 4:40
memberMember 1043982020-Aug-14 4:40 
GeneralRe: Need help Pin
Yogesh Kumar Tyagi20-Aug-14 18:08
professionalYogesh Kumar Tyagi20-Aug-14 18:08 
QuestionMy Vote of 5* Pin
Developer Rahul Sharma23-Jul-14 18:30
professionalDeveloper Rahul Sharma23-Jul-14 18:30 
AnswerRe: My Vote of 5* Pin
Yogesh Kumar Tyagi23-Jul-14 18:37
professionalYogesh Kumar Tyagi23-Jul-14 18:37 
QuestionIt can not be read by any bar code reader Pin
SDE EDP3-May-14 1:11
memberSDE EDP3-May-14 1:11 
QuestionRe: It can not be read by any bar code reader Pin
Member 1020823223-May-14 2:13
memberMember 1020823223-May-14 2:13 
AnswerRe: It can not be read by any bar code reader Pin
Yogesh Kumar Tyagi7-Jul-14 20:41
professionalYogesh Kumar Tyagi7-Jul-14 20:41 
AnswerRe: It can not be read by any bar code reader Pin
Member 102082328-Jul-14 3:31
memberMember 102082328-Jul-14 3:31 
GeneralRe: It can not be read by any bar code reader Pin
Yogesh Kumar Tyagi8-Jul-14 17:47
professionalYogesh Kumar Tyagi8-Jul-14 17:47 
AnswerRe: It can not be read by any bar code reader Pin
Member 107728264-Jul-14 3:18
memberMember 107728264-Jul-14 3:18 
AnswerRe: It can not be read by any bar code reader Pin
Yogesh Kumar Tyagi7-Jul-14 20:41
professionalYogesh Kumar Tyagi7-Jul-14 20:41 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160525.2 | Last Updated 25 Mar 2014
Article Copyright 2014 by Yogesh Kumar Tyagi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid