Creating Strongly Typed CheckBox List in ASP.NET MVC

This article will demonstrate the how to create strongly typed checkbox list in ASP.NET MVC application, So lets learn step by step about it.

Step 1 : Create an MVC Application.
Now let us start with a step by step approach from the creation of simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK . 
 Step 2 : Add Model class
Right click on model folder of created MVC application project and add  class named CheckBoxModel.cs
CheckBoxModel.cs
public class CheckBoxModel
    {
        public int Value { get; set; }
        public string Text { get; set; }
        public bool IsChecked { get; set; }
    }
    public class CheckBoxList
    {
        public List<CheckBoxModel> CheckBoxItems { get; set; }
    }
 Step 2 : Add Controller
Right click on Controllers folder of created MVC application and add Controller named HomeController.cs
 HomeController.cs
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //Creating object of CheckBoxList model class
            CheckBoxList ChkItems = new CheckBoxList();
            //Additng items to the list
            List<CheckBoxModel> ChkItem = new List<CheckBoxModel>()
            {
              new CheckBoxModel {Value=1,Text="ASP.NET",IsChecked=true },
              new CheckBoxModel {Value=1,Text="C#",IsChecked=false },
              new CheckBoxModel {Value=1,Text="MVC",IsChecked=false },
              new CheckBoxModel {Value=1,Text="Web API" ,IsChecked=false},
              new CheckBoxModel {Value=1,Text="SignalR",IsChecked=false },
              new CheckBoxModel {Value=1,Text="SQL" ,IsChecked=false},
            };
            //assigning records to the CheckBoxItems list 
            ChkItems.CheckBoxItems = ChkItem;
            return View(ChkItems);
           
        }

    }
 Step 3: Add View
Right click on View folder of created MVC application project and add empty view named Index.cshtml. Now open the Index.cshtml view and write the following code into the view
@model BindCheckBoxListInMVC.Models.CheckBoxList
@{
    ViewBag.Title = "www.compilemode.com";
}
<div class="form-horizontal">
    <h4>Select your favourite Subjects</h4>
        @foreach (var item in Model.CheckBoxItems)
        {
            <input id="chk@(item.Value)"
                   type="checkbox"
                   value="@item.Value" 
                   checked="@item.IsChecked" />
                @item.Text <br />
        }
       
</div>
Now everything is ready ,run the application then the check box list will be look like as follows .
From all above example we have learned how to create strongly typed checkbox list in ASP.NET MVC.
Summary
I hope this article is useful for all readers, if you have a suggestion then please contact me.
Don't Forget To  

Related articles

Routing in ASP.NET MVC

In today's modern web application each and every thing is important including request URL pattern of the application to make application more traffic driven and user friendly. In earlier ASP.NET application all the user request are mapped with physical file location that is with .aspx pages. These types of URL pattern are won't be customized to make it user, SEO friendly and most of the time in ASP.NET application to overcome these URL drawback URL rewriting technique is used, But still it unable to fulfill the expected requirement.
In ASP.NET MVC, URL pattern is completely different as compare to the ASP.NET application URL pattern, So lets learn about the ASP.NET MVC routing.

What is routing in ASP.NET MVC ?
Routing is the concept in ASP.NET MVC which is used to define the URL pattern for the ASP.NET MVC application incoming user request.
There are two types of routing supported by ASP.NET MVC
  • Conventional based routing 
  • Attribute routing
Conventional Routing
The default routing in ASP.NET MVC is a conventional routing which is get added in RouteConfig.cs file when we create ASP.NET MVC application, These type of routing defined in RouteConfig.cs file .

The following is the default routing

Suppose we have Employee method in ASP.NET MVC application and we want to define the URL pattern that how this method can be called by end user then routing pattern can be defined as in the following

Attribute Routing
The routing which is defined on controller or action level is called as attribute routing . These type of routing is only supports in  MVC 5 version onward
I hope from preceding brief explanation you have learned about the ASP.NET MVC routing, In my next article we will learn each of the routing in details with real time examples.
    The preceding is the example of attribute routing which can be enabled in RouteConfig.cs by calling MapMvcAttributeRoutes method of RouteCollection class
    
    Key Points
    • RouteCollection class is used for routing which uses the System.Web.Routing namespace
    • ASP.NET MVC 5 supports two types of routing that is conventional and attribute routing
    • Conventional based is the default routing in ASP.NET MVC 
    • Attribute routing can be defined on controller as well as action level
    • All routes should be registered into the Global.asax file .
    • Every ASP.NET MVC application must have at least one routing defined
    • We can define multiple routing in single application in this case it executed sequence wise as it defined.
    • If we are defining two route templates then the route name must be different across the application level
    Summary
    I hope, this article is useful for all the readers. If you have any suggestions, please contact me. In my next article we will learn real time example of conventional and attribute routing.

    Don't Forget To  

    Top 10 Features of Visual Studio 2017

    Microsoft launches the Visual Studio 2017 with lots of features some them are even not predicated such as Visual studio can support other languages other than Microsoft origin and also Visual studio can be get installed on other operating system than the Microsoft windows operating system, Now all is possible you can installed visual studio on Linux & Mac OS as well also you can develop the application using multiple open source languages which are not developed by Microsoft .
    Microsoft changing lot day by day by making visual studio universal application development platform using any programming language. Visual studio 2017 comes with the following editions which can be installed on Windows and Mac operating system
    • Visual Studio Community
    • Visual Studio Professional
    • Visual Studio Enterprise
    • Visual Studio Code
    Visual Studio Community

    This is a free edition having fully featured which can be used for students, open-source project contribution, individual developers and non-enterprise organization having not more than five users.
    Visual Studio Professional
    This is a commercial editions having Professional developer tools, services, and subscription benefits for small teams which can be used by purchasing the licensed copy.
    Visual Studio Enterprise
    This is a commercial editions having the features to meet end-to-end solution where high demand of quality and scale the team in all sizes. enterprise edition can be used by purchasing license.
    Visual Studio Code
    This is a Free, open source edition of visual studio which cab be used to develop the application using wide range of open source programming languages. Visual studio code can be installed on Mac, Windows and Linux operating system.
    Let's learn about top 10 features of visual studio 2017 which can be differ from edition to edition
    Install what you wants
    Now you can install the specific components whatever you wants which makes visual studio installation much  faster than previous edition
    Contentious Integration and Deployment (DevOps)
    Now you can configure CI-CD pipeline directly from the visual studio IDE itself
    Integration with Cloud
    You can integrate all visual studio developed application to Microsoft azure such as you can deploy your application on Microsoft azure directly from the visual studio and lot more
    Lightweight Solution Load
    Now you can load the projects in visual studio solution explorer very faster using lightweight solution load feature which is useful when your project solution contains multiple projects.
    Live Unit Testing
    Now you can test your code once you save your changes in visual studio editor instead of running test methods separately, This feature can help to fix the code issue while doing the real time development instead of fixing it later & change your code again.
    Enforcing code styles and conventions
    Now you can define your coding style and conventions directly from the visual studio and force developer to follow your defined coding standards which will help to achieve uniformity in coding standards across your project team developers.
    Architectural Dependency Validation
    Now you can validate your project architectural dependencies which will helpful to remove the unwanted  dependencies from your project & improve the performance as well as security.
    Improvements to code navigation
    Now can navigate easily into the code from visual studio to search classes and methods of  your project also visual studio 2017 makes very easier to find all references of particular variable or methods of your project.
    IntelliSense filtering
    Now you can filter the intellisense and find the appropriate properties and methods very easily.
    The revised Start page
    Click to Run Debugging
    Now you can debug your specific line of code without setting the debug point with the help of click to run feature.
    Summary
    I hope this article is useful for all readers, In my next article we will learn in details of each feature, If you have any suggestions please contact me.
     
    Don't Forget To 

    Mapping Stored Procedure Parameter with Dapper ORM Using DynamicParameters

    In this article we will learn how to map stored procedure parameter with Dapper ORM using DynamicParameters class of Dapper, Let's demonstrate it with step by step examples,
    Suppose you have following model class which values assigned from UI

    public class EmpModel
        {
            [Display(Name = "Id")]
            public int Empid { get; set; }
            [Required(ErrorMessage = "First name is required.")]
            public string Name { get; set; }
            [Required(ErrorMessage = "City is required.")]
            public string City { get; set; }
    
            [Required(ErrorMessage = "Address is required.")]
            public string Address { get; set; }
        }


    Now consider following stored procedure we have

    Create procedure [dbo].[AddNewEmpDetails]  
    (  
       @Name varchar (50),  
       @City varchar (50),  
       @Address varchar (50)  
    )  
    as  
    begin  
       Insert into Employee values(@Name,@City,@Address)  
    End  


    Now following is the function which is used to map the stored procedure with Dapper

       public bool AddEmployee(EmpModel obj)
            {     
                    DynamicParameters param = new DynamicParameters();
                    param.Add("@Name", obj.Name);
    param.Add("@City", obj.City);
    param.Add("@Address",obj.Address);
                    connection();
                    con.Open();
                    con.Execute("AddNewEmpDetails", param, commandType: CommandType.StoredProcedure);
                    con.Close();
                    return true;         
            }
     
    
    
    
    
    In the above function
    •  Connection() is the method which contains the connection string .
    •  Con is the SqlConnection class object.
    • AddNewEmpDetails is the stored procedure.
    •  DynamicParameters is the Dapper class name to map parameter like as SqlCommand
    • EmpModel is  model class.
    Summary
    I hope this article is useful for all readers. If you have any suggestions please contact me.Don't Forget To  


    Upload Images on Server Folder Using ASP.NET MVC

    Sometimes we require to upload the images on the server folder for specific requirement so by considering this requirement I have decided to write this article, Let's demonstrate step by step  
    Step 1: Create an MVC Application.
    Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. Click "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
     Step 2: Create Model Class
    Now let us create the model class named FileUploadModel.cs by right clicking on Models folder as in the following screenshot:

    Write the following code into the FileUploadModel.cs as follows

    FileUploadModel.cs 
    public class FileUploadModel   
          {    
              [DataType(DataType.Upload)]    
              [Display(Name = "Upload File")]    
              [Required(ErrorMessage = "Please choose file to upload.")]    
              public string file { get; set; }    
            
          }   
    
    Step 3 : Add Controller Class.

    Now let us add the MVC 5 controller as in the following screenshot:

     After clicking on Add button it will show the window. Specify the Controller name as FileUpload with suffix Controller.
    Note:
    The controller name must be having suffix as 'Controller' after specifying the name of controller. Now lets modify the default code in FileUploadController.cs to read uploaded files .
    There are many ways to read the uploaded files in controller but in this article we will learn two ways to read the uploaded files into the controller which are listed below,
    • HttpRequestBase: We can use HttpRequestBase class property named Request to get collection of files or single file.
    • HttpPostedFileBase: This is the easiest way to read the uploaded files into the controller .
    Now let's open the FileUploadController.cs class file and write the following code to read file using HttpRequestBase class.

    FileUploadController.cs
     
    [HttpPost]    
               public ActionResult UploadFiles(HttpPostedFileBase file)    
               {    
                   if (ModelState.IsValid)    
                   {    
                       try    
                       {    
                             
                           //Method 2 Get file details from HttpPostedFileBase class    
            
                           if (file != null)    
                           {    
                               string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                               file.SaveAs(path);     
                           }    
                           ViewBag.FileStatus = "File uploaded successfully.";    
                       }    
                       catch (Exception)    
                       {      
                           ViewBag.FileStatus = "Error while file uploading."; ;    
                       }                  
                   }    
                   return View("Index");    
               }  
    

    Following is the whole source code of FileUploadController.cs file which will look like as follows,

        using System;    
        using System.IO;    
        using System.Web;    
        using System.Web.Mvc;    
            
        namespace UploadingFilesUsingMVC.Controllers    
        {    
            public class FileUploadController : Controller    
            {    
                // GET: FileUpload    
                public ActionResult Index()    
                {    
                    return View();    
                }    
                [HttpPost]    
                public ActionResult UploadFiles(HttpPostedFileBase file)    
                {    
                    if (ModelState.IsValid)    
                    {    
                        try    
                        {    
                              
            
                            if (file != null)    
                            {    
                                string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                                file.SaveAs(path);    
            
                            }    
                            ViewBag.FileStatus = "File uploaded successfully.";    
                        }    
                        catch (Exception)    
                        {    
            
                            ViewBag.FileStatus = "Error while file uploading.";    
                        }    
                         
                    }    
                    return View("Index");    
                }    
            }    
        }   
    
    Step 4 : Creating view named Index using FileUploadModel class .

    Right click on View folder of created application and choose add view, select FileUploadModel class and choose create scaffolding template,
    Click on Add button, then it will create the view named index. Now open the Index.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,
    Index.cshtml

    @model UploadingFilesUsingMVC.Models.FileUploadModel
    
    @{
        ViewBag.Title = "www.compilemode.com";
    }
    
    @using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} })
                    @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
                </div>
            </div>
            
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Upload" class="btn btn-primary" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10 text-success">
                    @ViewBag.FileStatus
                </div>
            </div>
        </div>
    }
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    

    Step 4 : Create a folder named UploadedFiles or as you wish to save uploaded files,
    Right click on created ASP.NET MVC application, solution explorer and choose add new item, then Add New Folder. After adding the model, view, controller and UploadedFiles folder to save the file. Solution explorer will look like as follows,


    Now we have done all coding to upload files.
    Step 5: Now run the application. After running the application initial screen will look as follows,

     Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,

     Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,

    Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,

    I hope from all the preceding examples we have learned how to upload files on server folder .
    Note:

    • HttpPostedFileBase instance name must be a file.
    • Model class property name must be file so it can generate the input type file .
    • Its important to define enctype = "multipart/form-data" in form action otherwise file value will be null in controller .
    • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
    Summary
    I hope this article is useful for all readers. If you have any suggestions please contact me.
    Don't Forget To 

    Bind Country List Using CultureInfo In ASP.NET MVC

    In this article we will learn how to populate list of countries using C# globalization class which is capable to display the countries list.

    Now let's start creating a simple MVC  application to demonstrate how to get list of countries without database in ASP.NET MVC using Globalization class

    Step 1: Create an MVC Application.

    Now let us start with a step by step approach from the creation of a simple MVC application as in the following,
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear,

    Step 2: Add Controller Class

    Now let us add the MVC 5 controller as in the following screenshot,

    After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.
    Now modify the default code in HomeController.cs class file and create the action methods, after modifying the code will look like as follows,
    HomeController.cs
     
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web.Mvc;
    
    namespace DisplayCountryList.Controllers
    {
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                List<string> CountryList = new List<string>() ;
                CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
                foreach (CultureInfo CInfo in CInfoList)
                {
                    RegionInfo R = new RegionInfo(CInfo.LCID);
                    if (!(CountryList.Contains(R.EnglishName)))
                    {
                        CountryList.Add(R.EnglishName);
                    }
                }
    
                CountryList.Sort();
                ViewBag.CountryList = CountryList;
                return View();
            }
        }
    }

    Step 3: Create View

    Right click on view folder or near Index Action method and Add view with name Index and modify the existing view code , After modifying the code the Index.cshtml will be look like as follows

    @{
        ViewBag.Title = "www.compilemode.com";
    }
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <hr />
            <div class="form-group">
                <label class="col-md-2 control-label">Select Country</label>
                <div class="col-md-10">
                    @Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList),new {@class = "form-control" })
                </div>
            </div>
    
            
        </div>
    }
    
    
    In the preceding code snippet we are binding DropDownList with ViewBag in which country list is assigned into the controller class.
    Step 4: Run application
     Now run the application we will see dropdownlist having list of countries as shown in the following screen shot


    Now Expand dropdownlist to see the other counties as shown in the following screen shot


    I hope from all the preceding examples,  you learned how to display country list without Database in ASP.NET MVC.
    Note:
    • Perform changes in code as per your requirement  its just example .
    • Follow proper standards which might be not meet with this given code.
    • It will not display all county list but its shows list major around 144 countries .
    Summary
    I hope this article is useful for all readers, If you have a suggestion then please contact me.
    Don't Forget To 

    Hosting ASP.NET MVC Application On IIS

    In my previous articles we have learned how to create MVC application and how to publish ASP.NET MVC application, Now in this article we will learn how to host ASP.NET MVC application on IIS . Hosting is required to make any application accessible to the end-user publicly on web. So, in this article, we will learn how to host ASP.NET  MVC application in IIS 10. The following steps are required to host any application.
    If you don't know how to develop and publish ASP.NET MVC application then please refer to following step by step tutorial link to learn about it.
    I hope you have learned required two steps that is developing and publishing ASP.NET MVC application, Now lets start hosting MVC application on IIS.

    Move the published code on Hosting Server
     
    Copy the "Published files" which we have seen in our previous article Publishing ASP.NET MVC Application Using File System and paste those on respective Servers where you want to host the ASP.NET MVC application. In our last article we have published ASP.NET MVC application in the E drive of my Server, as shown in the following image .



    Open IIS Manager
     
    Now, open the IIS Manager from Windows menu or in any other ways you have known.
     

    The above image is of IIS 10 Manager of my Windows 10 machine. The view as well as options might be different on your machine depending on the OS version.
     
    Add Website to host MVC application

    Right click on "Site" in IIS and click on add new website, as shown in the following screenshot.


    After clicking on "Add Website" option, it displays the following configuration window.
     
     
    I hope you understood the preceding configuration by highlighted text.
     
    Define Site Name & Application Pool
     
    Define the site name which will be useful to uniquely identify the site within the IIS server. After specifying the site name, choose the application pool from available pools. You can even create a custom application pool with any desired name. Currently, our IIS manager has the following application Pools.


    Choose the application pool depending on your application configuration. In this article, we are going to choose DefaultAppPool.
    Browse and select Published Folder path
    Now, choose the physical location of published code files by clicking on "Browse" button, as shown in the following image. 
     
     
     
    Now, click on "OK" button.
     
    Define IP address & Port
     
    Choose one IP address from the list of available IP addresses and define the unique port number for the application, which will be unique within the defined IP address.

    Choose Protocol & Host name (optional )
     
    Choose the protocol for your application i.e HTTP or HTTPS which requires port 443 to be open and choose the Host name which will be used publicly to access the application. After defining all the configurations, the web site configuration window will look like this.

    Now, click on OK button. It will create and add the application in IIS.
    Browse the application using web browser
    Browse the hosted application using your system (PC/Laptop) browser , Click on browse hyperlink which is  highlighted in the following image 
     

    After clicking on preceding IIS shown image browse hyperlink, then application will open in your default web browser as shown in the following image
     
     
     
    Preceding is our IIS hosted ASP.NET MVC application which is running in browser.

    Note
    • This article is just guideline to show how to host ASP.NET MVC web API application on IIS .
    • Optimize the speed by setting debug as false etc., from web.config file as per your skills. 
    • In this article, the optimization is not covered in depth.
    • Configure the authentication in IIS as per your requirement .
    Summary
    I hope, this article is useful for all the readers to learn about hosting ASP.NET MVC web application on IIS. If you have any suggestions, please contact me.

    Don't Forget To 

    Downloading Binary Files From SQL DataBase Using ASP.NET MVC

    This articles explains the step by step how to download the files in ASP.NET MVC from database which is stored in a binary format , So lets learn step by step so beginners also can also understand .

    Step 1 : View Binary formatted Uploaded Files

    Step 2: Create an MVC Application.
    Now, let us create a simple MVC application to download the uploaded  file as:
    1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
    2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK. After clicking, the following Window will appear:
    Step 3: Create Model Class
    Now, let us create the model class file, named FileDetailsModel.cs, by right clicking on Models folder and define the following properties  as:
    public class FileDetailsModel  
       {  
           public int Id { get; set; }  
           [Display(Name = "Uploaded File")]  
           public String FileName { get; set; }  
           public byte[] FileContent { get; set; }  
      
      
       }  
    Step 4 : Create Stored Procedure
    Now Create the stored procedure to view the uploaded files using following script as
    CREATE Procedure [dbo].[GetFileDetails]  
    (  
    @Id int=null  
    )  
    as  
    begin  
    select Id,FileName,FileContent from FileDetails  
    where Id=isnull(@Id,Id)  
    End  
     I hope same you have created ;
    Step 5 : Add Controller Class
    Now, let us add ASP.NET MVC controller, as shown in the screenshot, given below:

    After clicking Add button, it will show the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . After modifying the code of Homecontroller class, the code will look like:
    HomeController.cs
    using System;  
        using System.Collections.Generic;  
        using System.IO;  
        using System.Linq;  
        using System.Web;  
        using System.Web.Mvc;  
        using Dapper;  
        using System.Configuration;  
        using System.Data.SqlClient;
        using FileUploadDownLoadInMVC.Models;  
        using System.Data;  
          
        namespace FileUploadDownLoadInMVC.Controllers  
        {  
            public class HomeController : Controller  
            {  
                 
                #region Upload Download file  
                public ActionResult Index()  
                {  
                    return View();  
                }  
                       
                [HttpGet]  
                public FileResult DownLoadFile(int id)  
                {  
          
          
                    List<FileDetailsModel> ObjFiles = GetFileList();  
          
                    var FileById = (from FC in ObjFiles  
                                    where FC.Id.Equals(id)  
                                    select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();  
          
                    return File(FileById.FileContent, "application/pdf", FileById.FileName);  
          
                }  
                #endregion  
         
                #region View Uploaded files  
                [HttpGet]  
                public PartialViewResult FileDetails()  
                {  
                    List<FileDetailsModel> DetList = GetFileList();  
          
                    return PartialView("FileDetails", DetList);  
          
          
                }  
                private List<FileDetailsModel> GetFileList()  
                {  
                    List<FileDetailsModel> DetList = new List<FileDetailsModel>();  
          
                    DbConnection();  
                    con.Open();  
                    DetList = SqlMapper.Query<FileDetailsModel>(con, "GetFileDetails", commandType: CommandType.StoredProcedure).ToList();  
                    con.Close();  
                    return DetList;  
                }  
         
                #endregion       
                #region Database connection  
          
                private SqlConnection con;  
                private string constr;  
                private void DbConnection()  
                {  
                     constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
                     con = new SqlConnection(constr);  
          
                }  
                #endregion  
            }  
        }   
    The preceding code snippet explained everything to upload  PDF file into database , I hope you have followed the same .
     Step 6:  Create View
    Right click on View folder of the created Application and create view named Index and Partial view FileDetails , The code snippet of the view's is look like as following .
    Index.cshtml
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    @using (Html.BeginForm())  
    {  
        @Html.AntiForgeryToken()    
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10 text-success">  
                    @ViewBag.FileStatus  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-8">  
                    @Html.Action("FileDetails", "Home")  
      
                </div>  
            </div>  
        </div>  
    }  
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script src="~/Scripts/jquery.validate.min.js"></script>  
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
    FileDetails.cshtml
    @model IEnumerable<FileUploadDownLoadInMVC.Models.FileDetailsModel>  
    <table class="table table-bordered">  
        <tr>  
            <th class="col-md-4">  
                @Html.DisplayNameFor(model => model.FileName)  
            </th>  
              
            <th class="col-md-2"></th>  
        </tr>  
      
    @foreach (var item in Model) {  
        <tr>  
            <td>  
                @Html.DisplayFor(modelItem => item.FileName)  
            </td>  
              
            <td>  
                @Html.ActionLink("Downlaod", "DownLoadFile", new { id=item.Id })   
                 
            </td>  
        </tr>  
    }  
      
    </table> 
    Now, we have done all the coding.
    Step 7 - Run the Application
    After running the Application, the UI of the Application will look like as follows


    Now click on download button , then it will shows the following popup


    Choose to open or save the file , I have chosen to open the files , the contents of the files will be look like as follows


    I hope, from the preceding examples, you have learned, how to download binary formatted PDF files from database.
    Note
    • This article used dapper ORM to interact with the database. Thus, you need to install dapper ORM into the Application. If you don't know how to install dapper ORM in MVC, watch the video, using the link, given below-
    • Makes changes in web.config file connectionstring tag, based on your database location and configuration.
    • Since this is a demo, it might not be using the proper standards. Thus, improve it, depending on your skills.
    Summary
    I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

    Read related article
    Don't Forget To 

      www.CodeNirvana.in

      Protected by Copyscape Online Copyright Protection
      Copyright © Compile Mode