A 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 article shows how to generate a Bar Code in an ASP.NET MVC project. A Bar code has a unique pattern of parallel lines. This pattern represents a unique number and using this number we get information of a product that has this bar code.
To start this task you need the Font named "FREE3OF9.TTF" (Code 39 Font). You can download it from. http://www.free-barcode-font.com. Click on Download the Code 39 font package.
First of all we create a database table for storing, the barcode image or barcode number of the bar code. The design of the table follows. In the database table we store the bar code image as a binary string.

Now we create a model in the model folder for data accessing. Add the following code to the 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; }
- }
- }
- public ActionResult Index()
- {
- return 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>
- 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;
- }
- }
- }
- ProductDataContext context = new ProductDataContext();
- [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");
- }
- 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);
- }
- @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>

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

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

Muthu kumaranPosted Jan 20, 2023, 12:43 PM
Please send barcode39.cs file
David GurreroPosted Jan 21, 2019, 12:29 PM
The Code bar 39 is unreadable with any scanner, am I missing something?
David GurreroPosted Jan 16, 2019, 2:18 PM
Please send barcode39.cs file
Dinesh KumarPosted Jul 30, 2018, 6:49 AM
Please send me barcode39.cs file i m also getting error.
Rajdeep SinghPosted Apr 8, 2018, 2:59 AM
My barcode prints blurred images. looks like either resolution of image is low. Am i missing something? please help
Nirmal RoyPosted May 4, 2017, 8:11 AM
Please send me barcode39.cs file i m getting error.
Nirmal RoyPosted May 4, 2017, 8:09 AM
Barcode39.cs not found. please send me barcode39.cs
sagar shendarkarPosted Feb 13, 2017, 2:47 AM
I have A Barcode Image but its not getting printed.And Sometimes printed but not a proper way i have ,made int barSize =16;
Shrinath TekePosted May 2, 2016, 1:15 AM
where is the barcode39.cs i am not getting in the downloaded source file
Divya RPosted Aug 19, 2015, 6:38 AM
Barcode39.cs coding
Divya RPosted Aug 19, 2015, 6:38 AM
give code 39 method coding
Divya RPosted Aug 19, 2015, 6:31 AM
I cannt generate the image?? y
Divya RPosted Aug 19, 2015, 6:08 AM
code39 showing error this line
Divya RPosted Aug 19, 2015, 6:07 AM
i got result but cannot showing the barcode image
Divya RPosted Aug 19, 2015, 6:07 AM
pls telme
Divya RPosted Aug 19, 2015, 5:39 AM
showing error this line and_code39 place alsi
Divya RPosted Aug 19, 2015, 5:39 AM
//BarCodeImage = objbar.getBarcodeImage(objbar.generateBarcode(), model.Name)
vijesh cognisunPosted Aug 2, 2015, 6:16 AM
Thanks for the post. I have successfully integrated the source code on my machine and able to genate and display barcodes. But when I am unable to scan the barcode from BarCode Gun machine. Barcode device details:- Device Company Name: CareScan, Model No: C7010 ,Serial No: 1340320. Any help on this?
Yogesh TyagiPosted Mar 25, 2014, 11:33 AM
pls download source code file and see it
Mahesh Kumar AlankaPosted Mar 23, 2014, 4:37 PM
your Description is not clear. please make changes in description for this project