Generate Bar Code in ASP.Net MVC 4

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.

  1. namespace BarCode.Models  
  2. {  
  3.     public class BarCodeModel  
  4.     {  
  5.         public int Id { getset; }  
  6.         public string Name { getset; }  
  7.         public string Description { getset; }  
  8.         public byte[] BarcodeImage { getset; }  
  9.         public string Barcode { getset; }  
  10.         public string ImageUrl { getset; }  
  11.     }  
  12. } 
Now open Visual Studio 2012 then select "New project" in the Start Page and click on ASP.NET MVC4 Web Application in Visual C#, name the project BarCode or whatever you like. Create a controller named HomeController and in this controller create an ActionResult method named Index.
  1. public ActionResult Index()  
  2. {  
  3.   return View();  
  4. } 
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 to create an insert form using @html helper or create a strongly typed view.
  1. @model BarCode.Models.BarCodeModel  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5. <h2>Index</h2>  
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.ValidationSummary(true)  
  9.     <fieldset>  
  10.         <legend>Add Product</legend>  
  11.         <div class="editor-label">  
  12.             @Html.LabelFor(model => model.Name)  
  13.         </div>  
  14.         <div class="editor-field">  
  15.             @Html.EditorFor(model => model.Name)  
  16.             @Html.ValidationMessageFor(model => model.Name)  
  17.         </div>  
  18.         <div class="editor-label">  
  19.             @Html.LabelFor(model => model.Description)  
  20.         </div>  
  21.         <div class="editor-field">  
  22.             @Html.EditorFor(model => model.Description)  
  23.             @Html.ValidationMessageFor(model => model.Description)  
  24.         </div>  
  25.         <p>  
  26.             <input type="submit" value="Create" />  
  27.         </p>  
  28.     </fieldset>  
  29. }  
  30. <div>  
  31.     @Html.ActionLink("Back to List""Index")  
  32. </div> 
For generating the bar code we are adding two classes, the first is “barcodecs” and the other is “BarCode39”. The Barcodecs class has two methods the first is “generateBarcode” for generating a unique bar code number and another method is “getBarcodeImage” creating the bar code image using “Code 39 Font”.

The “barcode39.cs” code is available in the given source code file. The barcodecs.cs code is the following.
  1. namespace BarCode.Models  
  2. {  
  3.     public class barcodecs  
  4.     {  
  5.         public string generateBarcode()  
  6.         {  
  7.             try  
  8.             {  
  9.                 string[] charPool = "1-2-3-4-5-6-7-8-9-0".Split('-');  
  10.                 StringBuilder rs = new StringBuilder();  
  11.                 int length = 6;  
  12.                 Random rnd = new Random();  
  13.                 while (length-- > 0)  
  14.                 {  
  15.                     int index = (int)(rnd.NextDouble() * charPool.Length);  
  16.                     if (charPool[index] != "-")  
  17.                     {  
  18.                         rs.Append(charPool[index]);  
  19.                         charPool[index] = "-";  
  20.                     }  
  21.                     else  
  22.                         length++;  
  23.                 }  
  24.                 return rs.ToString();  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);  
  29.             }  
  30.             return "";  
  31.         }  
  32.         public Byte[] getBarcodeImage(string barcode, string file)  
  33.         {  
  34.             try  
  35.             {  
  36.                 BarCode39 _barcode = new BarCode39();  
  37.                 int barSize = 16;  
  38.                 string fontFile = HttpContext.Current.Server.MapPath("~/fonts/FREE3OF9.TTF");  
  39.                 return (_barcode.Code39(barcode, barSize, true, file, fontFile));  
  40.             }  
  41.             catch (Exception ex)  
  42.             {  
  43.                 //ErrorLog.WriteErrorLog("Barcode", ex.ToString(), ex.Message);  
  44.             }  
  45.             return null;  
  46.         }  
  47.     }  
  48. } 
Now create a HttpPost Action method to get the posted data. I am using “LINQ to SQL” (dbml file) to insert data into the table.

Now create a data context for making a connection to the database.
  1. ProductDataContext context = new ProductDataContext();
Now create an object of the product table for inserting data into the table and write the following code for the action method. Here barcode is a unique number that is generated by the generateBarcode() method and the barcode image is byte codes of an image generated by the getBarCodeImage() method of the of barcodecs.cs as in the following:
  1. [HttpPost]    
  2. public ActionResult Index(BarCodeModel model)    
  3. {    
  4.      barcodecs objbar = new barcodecs();    
  5.      Product objprod = new Product()    
  6.      {    
  7.           Name = model.Name,    
  8.           Description = model.Description,    
  9.           Barcode = objbar.generateBarcode(),    
  10.           BarCodeImage =   objbar.getBarcodeImage(objbar.generateBarcode(), model.Name)    
  11.     };    
  12.     context.Products.InsertOnSubmit(objprod);    
  13.     context.SubmitChanges();    
  14.     return RedirectToAction("BarCode""Home");    
  15. } 
Now create another action method to display the barcode. In this action method we get data from the database. The code is as in the following:
  1. public ActionResult BarCode()  
  2. {  
  3.        SqlConnection con = new SqlConnection("Data Source=192.168.137.1;Initial Catalog=Hospital;Persist Security Info=True;User ID=sa;Password=MORarka#1234");  
  4.        string query = "select * From Product";     
  5.        DataTable dt = new DataTable();  
  6.        con.Open();  
  7.        SqlDataAdapter sda = new SqlDataAdapter(query, con);  
  8.        sda.Fill(dt);  
  9.        con.Close();  
  10.        IList<BarCodeModel> model = new List<BarCodeModel>();  
  11.        for (int i = 0; i < dt.Rows.Count; i++)  
  12.        {  
  13.             var p = dt.Rows[i]["BarCodeImage"];  
  14.             model.Add(new BarCodeModel()  
  15.             {  
  16.                 Name = dt.Rows[i]["Name"].ToString(),  
  17.                 Description = dt.Rows[i]["Description"].ToString(),  
  18.                 Barcode = dt.Rows[i]["Barcode"].ToString(),  
  19.                 ImageUrl = dt.Rows[i]["BarCodeImage"] != null ? "data:image/jpg;base64," + Convert.ToBase64String((byte[])dt.Rows[i]["BarCodeImage"]) : ""  
  20.            });  
  21.       }  
  22.       return View(model);  
  23. } 
Now right-click on the BarCode() action method and add a new view to display the barcode. Write the following code in BarCode.cshtml to display the data.
  1. @model IEnumerable<BarCode.Models.BarCodeModel>  
  2. @{  
  3.     ViewBag.Title = "BarCode";  
  4. }  
  5. <h2>BarCode</h2>  
  6. <p>  
  7.     @Html.ActionLink("Create New""Create")  
  8. </p>  
  9. <table>  
  10.     <tr>  
  11.         <th>  
  12.             @Html.DisplayNameFor(model => model.Name)  
  13.         </th>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Description)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Barcode)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.ImageUrl)  
  22.         </th>  
  23.         <th></th>  
  24.     </tr>  
  25. @foreach (var item in Model) {  
  26.     <tr>  
  27.         <td>  
  28.             @Html.DisplayFor(modelItem => item.Name)  
  29.         </td>  
  30.         <td>  
  31.             @Html.DisplayFor(modelItem => item.Description)  
  32.         </td>  
  33.         <td>  
  34.             @Html.DisplayFor(modelItem => item.Barcode)  
  35.         </td>  
  36.         <td>  
  37.            <img src="@item.ImageUrl"/>  
  38.         </td>  
  39.     </tr>  
  40. }  
  41. </table> 
Now build and run your application.


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.


Similar Articles