Video: Connecting To Microsoft Azure SQL DataBase ( Cloud ) Using SSMS

In previous video tutorial Creating Azure SQL DataBase (Cloud ) Step by Step  We have leaned how to create Azure SQL DataBase , Now this video tutorial guides you how to connect our created Azure SQL DataBase (cloud) using SQL Server management studio . This video tutorial covers the following topics
  • What is SQL Server Management studio?
  • Configuring firewall.
  • Restrict & Allow Client Machines to Access DataBase.
  • Map Client IP Address .
  • Why we need to MAP Client IP Address.
Now Let's watch

Summary
I hope this video tutorial is useful for all viewers , If you like this video then , don't forget to subscribe compilemode.com YouTube Channel.

SubScribe To Youtube Channel

Disable Mouse Right Click on Entire ASP.NET MVC Application

Most challenging task in today's application is to secure them from many types of attacks and as developer our job is to provide full security as we have possible in various ways. In this article we will learn how to disable mouse right click using different ways .So considering the preceding requirement I have decided to write this article .Now let's learn step by step, which helps beginners to learn how to disable mouse right click on entire ASP.NET MVC application. 

Create an MVC Application.

Now let us start with a step by step approach from the creation of a simple MVC application
  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 then choose the empty application and check on MVC option  .
    If don't know how to create ASP.NET MVC application then you can refer previous articles with the help of following link.
    I hope you have created ASP.NET MVC Application, there are many ways to disable mouse right click and each one of them has pros and cons , the following are commonly used approaches.
    • Using contextmenu in Body tag
    • Using contextmenu with jQuery.
    • Using JavaScript .

    Using oncontextmenu in Body tag

     This is the shortest way to disable mouse right click without writing any script code but by default it uses javascript .
    To use it , just called the contextmenu function in page body tag or master page body tag to disable the mouse right click as
    Example

     In the preceding example , the function is called in layout body tag hence it will disable mouse right click on entire ASP.NET application, If you wants to disable only page specific then you can call same function in specific page.
     Disadvantage of this approach is it wont be work outside the body tag , if click on outside of text then it will allows to mouse right click .

      Using contextmenu with jQuery

    This is the best way to disable the mouse right click which supports on every browser and won't be allow for mouse right click.

    Example
      
    <script>
            $(document).ready(function () {
    
                $(this).bind("contextmenu", function (e) {
    
                    e.preventDefault();
                   
                });
    
    
            });
          
        </script>
    Call preceding function inside the body tag of layout page if you wants to disable mouse right click on entire ASP.NET MVC application.
    Now open the layout page of our created application and add preceding function inside the layout body tag .after modifying the code the layout page source code will be look like as shown in following example.

    _Layout.cshtml

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - www.compilemode.com</title>
        <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
        <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
        
    
        <script src="~/Scripts/jquery-3.1.0.min.js"></script>
        <script src="~/Scripts/bootstrap.min.js"></script>
       
    
       
    </head>
    <body>
      
        <script>
            $(document).ready(function () {
    
                $(this).bind("contextmenu", function (e) {
    
                    e.preventDefault();
                   
                });
    
    
            });
          
        </script>
    
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("www.compilemode.com", "www.compilemode.com", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                    </ul>
                </div>
            </div>
        </div>
    
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>&copy; @DateTime.Now.Year -www.compilemode.com</p>
            </footer>
        </div>
        
       
        
    </body>
    </html>

    Now create on empty view named Index to check the whether mouse right click disable or not .

    Index.cshtml

    @{     ViewBag.Title = "www.compilemode.com"; } 
    <hr />
    Visit <a href="https://www.blogger.com/null">www.compilemode.com</a> to learn more about Microsoft Technologies. 
    <hr />
    Now we have done with the code .After running the application in the browser it shows the following output  

    Without alert Box

    Right click on page , it will not show you mouse right click , it means it disable for page level as wel as on entire ASP.NET MVC application. 

     With Alert Box

    If you wants to show alert Box then just call alert function in our created jQuery function after e.preventDefault() function .


     Note:
    • Its not good practice to show user mouse right click alert box because of this we exposing our security measurement what we had done so its always good to do not show alert box.
    • To use jQuery  we need to add the reference for the jQuery library .You can download the latest jQuery library from http://jquery.com/download/.
    From preceding all example we have learned how to to disable mouse right click on page specific as well as on entire application .
    Summary
    I hope this article is useful for all readers, If you have any suggestion related to article then please contact me.

    Related articles

    Video : Creating Azure SQL DataBase (Cloud ) Step by Step

    This video tutorial guides you to create SQL Azure DataBase step by step  which covers the following topics
    • What is SQL Azure
    • Creating Azure SQL Database.
    • Creating Server .
    • Choosing SQL Data center Server location .
    Now Let's watch


    Summary 

    I hope this video tutorial is useful for all viewers , If you like this video then , don't forget to subscribe compilemode.com YouTube Channel.

    SubScribe To Youtube Channel

    Show Multiple Table Data on View In ASP.NET MVC

    In earlier ASP.NET it was very straightforward and easy to display multiple tables data using Dataset but in ASP.NET MVC we need to mostly work with generic lists. Also in many forum posts and in my event speaking people asking me how to display multiple tables data in single view from database in ASP.NET MVC . So considering the preceding requirement I have decided to write this article .Now let's learn step by step, which helps beginners to learn how to display multiple tables data in single view from database in ASP.NET MVC.
    Scenario
    Lets consider we have a requirement  to display the master data in single view where Data coming from multiple tables . So in this scenario we need to create complex model class from multiple model classes.We have following two tables in Database from which we are going to display the data as in following screen shots.


    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 The Reference of Dapper ORM into Project.
    Now the next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
    1. Right click on Solution ,find Manage NuGet Package manager and click on it.
    2. After as shown into the image and type in search box "dapper".
    3. Select Dapper as shown into the image .
    4. Choose version of dapper library and click on install button.

    Step 3: Create Model Class
    Now let us create the model class file named CustomerModel.cs by right clicking on model folder as in the following screenshot:

     Note:

    It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class library.
    CustomerModel.cs class file code snippet:
    using System.Collections.Generic;  
      
    namespace GetMultipleTableRecordsUsingDapper.Models  
    {  
        public  class Customer  
        {  
            public string Name { get; set; }  
            public string CustomerType { get; set; }  
            public string Gender { get; set; }  
      
        }  
        public class Region  
        {  
            public string Country { get; set; }  
            public string State { get; set; }  
            public string City { get; set; }  
        }  
        public class MasterDetails  
        {  
            public List<Customer> CustPersonal { get; set; }  
            public List <Region> CustRegions { get; set; }  
      
        }  
    }  
    Step 4: 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 Customer with suffix Controller.
    Note:
    • Controller name must be having suffix as 'Controller' after specifying the name of controller.
    Step 5 : Create  Stored procedure.
    Create the stored procedure to get the multiple table records from database as,
    Create PROCEDURE GetMasterDetails  
    as  
    BEGIN  
          
        SET NOCOUNT ON;  
      
     Select Name,CustomerType,Gender  from CustomerMaster  
     Select Country,State,City from RegionMaster  
    END  
    Run the preceding script in sql it will generates the stored procedure to get the multiple table records from database .
    Step 6: Create Repository class.
    Now create Repository folder and Add CustomerRepo.cs class for database related operations, Now create methods in CustomerRepo.cs to get the multiple table data from stored procedure with the help of Dapper ORM as in the following code snippet:
    CustomerRepo.cs
    using Dapper;  
    using GetMultipleTableRecordsUsingDapper.Models;  
    using System.Collections.Generic;  
    using System.Configuration;  
    using System.Data;  
    using System.Data.SqlClient;  
    using System.Linq;  
      
    namespace GetMultipleTableRecordsUsingDapper.Repository  
    {  
        public class CustomerRepo  
        {  
            //To Handle connection related activities   
            SqlConnection con;  
            private void connection()  
            {  
                string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();  
                con = new SqlConnection(constr);  
            }  
            /// <summary>  
            /// Get Multiple Table details  
            /// </summary>  
            /// <returns></returns>  
            public IEnumerable<MasterDetails> GetMasterDetails()  
            {  
                connection();  
                con.Open();  
                var objDetails = SqlMapper.QueryMultiple(con, "GetMasterDetails",commandType: CommandType.StoredProcedure);  
                  MasterDetails ObjMaster = new MasterDetails();  
      
                //Assigning each Multiple tables data to specific single model class  
                ObjMaster.CustPersonal = objDetails.Read<Customer>().ToList();  
                ObjMaster.CustRegions = objDetails.Read<Region>().ToList();  
      
                List<MasterDetails> CustomerObj = new List<MasterDetails>();  
                //Add list of records into MasterDetails list  
                CustomerObj.Add(ObjMaster);  
                con.Close();  
                  
                return CustomerObj;  
      
            }  
        }  
    }  
    Note
    1. In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
    Step 7: Create Method into the CustomerController.cs file.
    Now modify the default code in CustomerController.cs class file to bind multiple HTML tables in single view from strongly typed complex model class with list of records, After modifying code will look like as follows,
    CustomerController.cs
    using GetMultipleTableRecordsUsingDapper.Models;  
    using GetMultipleTableRecordsUsingDapper.Repository;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
    namespace GetMultipleTableRecordsUsingDapper.Controllers  
    {  
        public class CustomerController : Controller  
        {  
            // GET: Customer  
            public ActionResult MasterDetail()  
            {  
                CustomerRepo objDet = new CustomerRepo();  
                 MasterDetails CustData = new MasterDetails();  
      
                List<MasterDetails> MasterData = objDet.GetMasterDetails().ToList();  
      
                CustData.CustPersonal = MasterData[0].CustPersonal;  
                CustData.CustRegions = MasterData[0].CustRegions;  
                 
      
                return View(CustData);  
            }  
        }  
    }  
    Step 8 : Creating strongly typed view named MasterDetail using MasterDetails class .
    Right click on View folder of created application and choose add view , select MasterDetails class and choose 'create' scaffolding template as


    Click on Add button then it will create the view named MasterDetail, Now open the MasterDetail.cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like as in the following,
    MasterDetail.cshtml


    @model GetMultipleTableRecordsUsingDapper.Models.MasterDetails  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    @using (Html.BeginForm())  
    {  
        <div class="form-horizontal">  
          <hr />  
            <div class="form-group">  
                <h5 class="btn btn-primary">Customer Type Master</h5>  
                <div class="col-md-12">  
                    <table class="table table-hover col-md-3">  
                         
                            <tr>  
                                <th>  
                                    Name  
                                </th>  
                                <th>  
                                    Customer Type  
                                </th>  
                                <th>  
                                    Gender  
                                </th>  
      
                            </tr>  
                          
                          
                        @{  
                            //To make unique Id  
                            int i = 0;  
                            foreach (var item in Model.CustPersonal)  
                            {  
      
                                <tr>  
                                    <td>  
      
      
                                        @Html.EditorFor(o => o.CustPersonal[i].Name, new { @id = "Name_" + i })  
                                    </td>  
                                    <td>  
                                        @Html.EditorFor(o => o.CustPersonal[i].CustomerType, new { @id = "NCustomerType_" + i })  
      
      
                                    </td>  
                                    <td>  
                                        @Html.EditorFor(o => o.CustPersonal[i].Gender, new { @id = "Gender_" + i })  
                                    </td>                               
      
                                </tr>  
                                i++;  
                            }  
                        }  
                    </table>  
                </div>  
            </div>  
            
            <div class="form-group">  
                <h5 class="btn btn-primary">Region Master</h5>  
                <div class="col-md-12">  
                    <table class="table table-condensed table-hover col-md-3">  
                        <tr>  
                            <th>  
                                Country  
                            </th>  
                            <th>  
                                State  
                            </th>  
                            <th>  
                                City  
                            </th>  
      
                        </tr>  
                        @{  
                            //To make unique Id  
                            int j = 0;  
                            foreach (var item in Model.CustRegions)  
                            {  
      
                                <tr>  
                                    <td>  
      
      
                                        @Html.EditorFor(o => o.CustRegions[j].Country, new { @id = "Country_" + j })  
                                    </td>  
                                    <td>  
                                        @Html.EditorFor(o => o.CustRegions[j].State, new { @id = "State_" + j })  
      
      
                                    </td>  
                                    <td>  
                                        @Html.EditorFor(o => o.CustRegions[j].City, new { @id = "City_" + j })  
                                    </td>  
      
                                </tr>  
                                j++;  
                            }  
                        }  
                    </table>  
                </div>  
            </div>  
            
        </div>  
     }  

    Common issues
    While binding list of records your control Id's must be unique , otherwise same first record will repeat in all list So to avoid this we need to maintain unique id's for control . As we have maintained in preceding view manually by using incremental i and j variable counter and model properties .
    Now after adding the Model, View and controller into our project. The solution explorer will look like as follows
     Now we have done all coding to upload files .

    Step 9 : Now run the application.
    After running the application then two table data will be shown in the following screen shot which look like as follows, 

    I hope from all preceding examples we have learned how to display multiple tables data in single view from database in ASP.NET MVC using Dapper ORM
    Note:

    • Download the Zip file of the sample application for a better understanding.
    • 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.
    Related articles

    Download Binary Format PDF Files From Database Using FileResult In ASP.NET MVC

    In previous article Upload PDF Files Into DataBase In Binary Format Using ASP.NET MVC  we have learned how to upload PDF files into database in binary format , Now in this article we will learn how to download those files using FileResult in ASP.NET MVC. 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

    Call Action Method Using Ajax Get Request in ASP.NET MVC

    In many forum post, I have read one common question that is how to make jQuery ajax GET request with input parameter in ASP.NET MVC , So by considering above requirement I have decided to write this article.
    Lest consider the scenario we have action method in named Details in Home controller which takes the Id as input parameter .Then jQuery function will be look like as follows.
    $(document).ready(function () {
            $("#btnGetDetails").click(function () {
                $.ajax({
                    //base address/controller/Action
                    url: 'http://localhost:51163/Home/Details',
                    type: 'GET',
                    data: {
                        //Passing Input parameter
                        id: $('#txtId').val()
                    },
                    success: function (result) {
                       //write something
                    },
                    error: function () {
                        alert("error");
                    }
                });
                return false;
            });
        });
    
    Suppose following is the Home controller having action result method named Details which takes id as input parameter.
    HomeController.cs
      public class HomeController : Controller
        {
            
            [HttpGet]
            public ActionResult Details(int id)
            {
            //write logic here to get data
    
            return View();
            }
        }
    Note
    • To work with jQuery we need to reference of jQuery library .You can use following CDN jQuery library from any provider such as Microsoft,Google or jQuery .
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
    To use above jQuery library you need an active internet connection , You can download and use it as offline .You need to be add reference as like below.
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    From preceding example we have learned how to make  jQuery Ajax GET request with input parameter in ASP.NET MVC.
    Summary
    I hope this article is useful for all readers, If you have a suggestion related to this article then please contact me.
     To learn ASP.NET MVC step by step please refer following articles

    DropDownList Using JSON Data In ASP.NET MVC

    Many times we need to bind the strongly typed DropDownList using JSON data in ASP.NET MVC . So by considering above requirement I have decided to write this article . Let us learn it step by step through creating a simple MVC application.
    Step 1: Create an MVC application.
    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.

    3. Choose MVC empty application option and click on OK
    Step 2: Add model class.

    Right click on model folder of created MVC application project and add class file named EmpModel.cs and create two classes as:

    EmpModel.cs
    using System.ComponentModel.DataAnnotations;  
      
    namespace BindDropDownListUsingJSON.Models  
    {  
        //Model property to the dropdownlist to get selected value  
        public class EmpModel  
        {  
            [Display(Name = "Select City")]  
            public string City { get; set; }  
        }  
        //to bind list of records to dropdownlist  
        public class DDLOptions  
        {  
           public int Id { get; set; }  
           public string CityName { get; set; }  
      
       }  
    }  
    Step 3: Add controller class.

    Right click on Controller folder in the created MVC application, give the class name Home or as you wish as in the following:


    Now after selecting controller template, click on Add button then the following window appears,



    Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as in the following:
    using BindDropDownListUsingJSON.Models;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
      
    namespace BindDropDownListUsingJSON.Controllers  
    {  
        public class HomeController : Controller  
        {  
            // GET: Home  
            public ActionResult Index()  
            {  
                return View();  
            }  
             
            //Return json list of cities  
            [HttpGet]  
            public JsonResult CityList()  
            {  
                List<DDLOptions> obj = new List<DDLOptions>()  
                {  
                    new DDLOptions {Id=1, CityName="Latur" },  
                    new DDLOptions {Id=2, CityName="Pune" },  
                    new DDLOptions {Id=4, CityName="Mumbai"},  
                    new DDLOptions {Id=5, CityName="New Delhi" }  
                }.ToList();  
      
                return Json(obj, JsonRequestBehavior.AllowGet);  
            }  
        }  
    }  
    In the above we have created two action methods one is return view named Index and another one will return json result named CityList. Remember that instead of going to the database I have created a list of records and return it as json. However you can bind this list from database but in this example assume that this list is coming from database.

    Step 4: Add View,

    Add strongly typed view named Index.cshtml from EmpModel class as:
     

    After clicking on add button the view generated.

    To call the CityList json action method, create the following jQuery Ajax function.
    <script>  
          
        $(document).ready(function ()  
        {    //call the CityList json result method  
            $.getJSON("/Home/CityList", function (data)  
            {        
                $.each(data, function (i, data)  
                {      // bind the dropdown list using json result              
                     $('<option>',  
                        {  
                            value: data.Id,  
                            text: data.CityName  
                        }).html(data.CityName).appendTo("#City");  
                    });  
            })  
            //Get the selected text on button click  
            $("#btnSave").click(function () {  
      
                var txt = $("#City option:selected").text();  
                
                // assign the selected value to span to   
                //show to the end user  
                $("#Spnmsg").text("Your Selected City is " + txt);  
      
                return false;  
      
            })  
      
        });  
    </script> 
    To work the above function properly we need the following jQuery file to be referenced at the top of the view or in layout page.
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    After adding necessary code, files and logic the Index.cshtml code will look like the following
    @model BindDropDownListUsingJSON.Models.EmpModel  
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
    <script>  
          
        $(document).ready(function ()  
        {    //call the CityList json result method  
            $.getJSON("/Home/CityList", function (data)  
            {        
                $.each(data, function (i, data)  
                {      // bind the dropdown list using json result              
                     $('<option>',  
                        {  
                            value: data.Id,  
                            text: data.CityName  
                        }).html(data.CityName).appendTo("#City");  
                    });  
            })  
            //Get the selected text on button click  
            $("#btnSave").click(function () {  
      
                var txt = $("#City option:selected").text();  
                
                // assign the selected value to span to   
                //show to the end user  
                $("#Spnmsg").text("Your Selected City is " + txt);  
      
                return false;  
      
            })  
      
        });  
    </script>  
      
    @using (Html.BeginForm())   
    {  
        @Html.AntiForgeryToken()  
          
        <div class="form-horizontal">  
             
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            <div class="form-group">  
                @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-12">  
                    @Html.DropDownListFor(model => model.City, Enumerable.Empty<SelectListItem>(), new { htmlAttributes = new { @class = "form-control" } })  
            
                     
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="Save" id="btnSave" class="btn btn-primary" />  
                </div>  
            </div>  
            <div class="form-group">  
                <div  class="col-md-offset-2 col-md-10 text-success">  
                    <span id="Spnmsg"></span>  
                   
                </div>  
            </div>  
        </div>  
    }  
    Step 5: Run the application.

    After running the application the output will be as in the following screenshot:

    In the preceding screenshot you have seen that drop down list records are populated from json data. Now select any city from drop down list records and click on save button, it will show the following output.
    From all the above examples, I hope you have learned how to bind strongly typed dropdownlist using JSON data in ASP.NET MVC .

    Note:
    • For the complete code, please download the sample zip file.
    • You need to use the jQuery library.
    Summary
    I hope this article is useful for all readers. If you have a suggestion then please contact me.

    Upload PDF Files Into DataBase In Binary Format Using ASP.NET MVC

    Many time we need to work with files and most of the time developers prefer to store files on physical location of server which is very difficult because it will consume lots of memory of server , So in this article we will learn how to upload files in binary format into database using ASP.NET MVC  . So lets learn step by step so beginners also can also understand .
    Step 1: Create an MVC Application.
    Now, let us start with a step by step approach from the creation of a simple MVC Application in the following:
    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 2: Create Model Class
    Now, let us create the model class file, named EmpModel.cs, by right clicking on Models folder and define the following properties  as:
    public class EmpModel  
       {  
           [Required]  
           [DataType(DataType.Upload)]  
           [Display(Name ="Select File")]  
           public HttpPostedFileBase files { get; set; }  
       }  
      
    
    Step 3 : Create Table and Stored Procedure
    Now Create the stored procedure and table to stored the uploaded files in binary format , Use the following script to create table named FileDetails as
    CREATE TABLE [dbo].[FileDetails](  
        [Id] [int] IDENTITY(1,1) NOT NULL,  
        [FileName] [varchar](60) NULL,  
        [FileContent] [varbinary](max) NULL  
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  

    As mentioned in preceding table script we have created three columns Id is for to identify files unique key , FileName for to store uploaded file name and FileContent to store uploaded file contents in binary format .
    Create the following Stored Procedure  to insert file details using the given script as

    Create Procedure [dbo].[AddFileDetails]  
    (  
    @FileName varchar(60),  
    @FileContent varBinary(Max)  
    )  
    as  
    begin  
    Set NoCount on  
    Insert into FileDetails values(@FileName,@FileContent)   
    End  

    In preceding we have created tables and stored procedures , I hope same you have created ;
    Step 4 : 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 FileUploadDownLoadInMVC.Models;  
    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 System.Data;  
      
    namespace FileUploadDownLoadInMVC.Controllers  
    {  
        public class HomeController : Controller  
        {  
             
           public ActionResult FileUpload()  
            {  
                return View();  
            }  
      
             
            [HttpPost]  
            public ActionResult FileUpload(HttpPostedFileBase files)  
            {  
      
             String FileExt=Path.GetExtension(files.FileName).ToUpper();  
      
                if (FileExt == ".PDF")  
                {  
                    Stream str = files.InputStream;  
                    BinaryReader Br = new BinaryReader(str);  
                    Byte[] FileDet = Br.ReadBytes((Int32)str.Length);  
      
                    FileDetailsModel Fd = new Models.FileDetailsModel();  
                    Fd.FileName = files.FileName;  
                    Fd.FileContent = FileDet;  
                    SaveFileDetails(Fd);  
                    return RedirectToAction("FileUpload");  
                }  
                else  
                {  
      
                    ViewBag.FileStatus = "Invalid file format.";  
                    return View();  
      
                }  
                 
            }  
             
            private void SaveFileDetails(FileDetailsModel objDet)  
            {  
      
                DynamicParameters Parm = new DynamicParameters();  
                Parm.Add("@FileName", objDet.FileName);  
                Parm.Add("@FileContent", objDet.FileContent);  
                DbConnection();  
                con.Open();  
                con.Execute("AddFileDetails", Parm, commandType: System.Data.CommandType.StoredProcedure);  
                con.Close();  
      
      
            }  
           
            private SqlConnection con;  
            private string constr;  
            private void DbConnection()  
            {  
                 constr =ConfigurationManager.ConnectionStrings["dbcon"].ToString();  
                 con = new SqlConnection(constr);  
      
            }  
        }  
    }  
    The preceding code snippet explained everything to upload  PDF file into database , I hope you have followed the same .
     Step 5:  Create strongly typed View
    Right click on View folder of the created Application and create  strongly typed view  for uploading files by choosing EmpModel.cs class , The code snippet of the view's is look like as following .
    FileUpload.cshtml
    @model FileUploadDownLoadInMVC.Models.EmpModel  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    @using (Html.BeginForm("FileUpload", "Home", 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.files, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })  
                    @Html.ValidationMessageFor(model => model.files, "", 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>

    Now, we have done all the coding.
    Step 6 - Run the Application
    After running the Application, the UI of the Application will look like as follows

    Now select PDF file from your system and click Upload button. It will upload the file in the database table which details look like as follows


    I hope, from the preceding examples, you have learned, how to upload PDF files in the binary format into the the database In ASP.NET MVC.
    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-
    • Its important to define enctype = "multipart/form-data" in form action, else the value will be null in the controller.
    • 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.

    www.CodeNirvana.in

    Protected by Copyscape Online Copyright Protection
    Copyright © Compile Mode