How To Generate Bar Code In ASP.NET MVC

In this article shows how to generate a Bar code in an ASP.NET MVC. 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.

First of all we create a database table. The design of the table follows. In the database table we store the bar code image as a binary string.

Bar Code Table

Now we create a project in ASP.NET MVC and then create a model. 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; }  
    }  
}

Now create a controller

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.

@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 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.

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)  
            {  
                throw ex;
            }  
            return "";  
        }  
        public Byte[] getBarcodeImage(string barcode, string file)  
        {  
            try  
            {  
                BarCode39 _barcode = new BarCode39();  
                int barSize = 16; 
                return (_barcode.Code39(barcode, barSize, true, file));  
            }  
            catch (Exception ex)  
            {  
                throw ex;
            }  
            return null;  
        }  
    }  
}

Now create a data context for making a connection to the database.

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:

[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 to display the barcode. In this action method we get data from the database. The code is as in the following:

public ActionResult BarCode()  
{  
       SqlConnection con = new SqlConnection("Your connection string");  
       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 the BarCode() action method and add a new view to display the barcode. Write the following code.

@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.

Index Page

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

Bar Code

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories