Filters In ASP.NET MVC

Security of the web application is very important to ensure valuable information is protected and not accessible to unauthorized user or entity . There are lots of techniques to maintain the security of the application which depends on security type scenario. So in this article we learn in brief about the ASP.NET MVC filters which are useful to maintain the security during the request processing.

Following are the filters provided by ASP.NET MVC to check the business logic and validation before and after executing the action methods or view results .
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters
Authorization filters
Used to authenticate request before executing the action method to ensure the request is authenticated and genuine. Authorization filter uses IAuthorizationFilter interface in which authorization filter methods are defined.
 Authorization filters has following built in filters
  1. Authorize
  2. RequireHttps
Action filters

Action filter useful to take some action before and after executing the action methods, This action filter implements the IActionFilter interface which includes the following methods .
  1. OnActionExecuting 
  2. OnActionExecuted
Result filters

Result filter useful to perform some action before and after executing view result, This action filter implements the IResultFilter interface which includes the following methods .
  1. OnResultExecuting 
  2. OnResultExecuted 
Result  filter has built in OutputCache filter.

Exception filters  

Exception filter responsible to manage unhanded exceptions which are occurred during the execution of ASP.NET MVC pipeline request . This filter is very useful to capture and log the exception details wherever you wants. This filter implements the IExceptionFilter interface also it has also  built in filter named HandleError.

These filter are executed in the following sequence
  1. Authorization filters 
  2. Action filters 
  3. Response filters 
  4. Exception filters 
Key Points
  • Filters are used to check some business logic before and after executing the action methods or view result. 
  • Each filter implements the its own interface methods.
  • Filters can be applied on Controller level , action method level as well as globally using filterconfig class
  • We can apply multiple filters on single controller or action method
  • If given ASP.NET MVC filter does not fulfill the our requirement then we can also create the custom filters using  FilterAttribute class.
  • Usually filters are registered in Global.asax file 
 I hope you have got brief understanding about the ASP.NET MVC filters , In my next article we will learn each of the filter in details with real time examples.
Summary
I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

Don't Forget To 

Insert Data into DataBase using ASP.NET MVC with ADO.NET

There are many techniques in ASP.NET MVC to insert the data into database including ORM such as Entity framework , Dapper etc and database access technology such as ADO.NET , In this article we will learn how to insert the data into database using ADO.NET in ASP.NET MVC application
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. After clicking, the following window will appear:
 As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application
Step 2: Create Model Class
Now let us create the model class named EmpModel.cs by right clicking on model folder and write the model properties inside the EmpModel.cs class after adding the properties the class will be look like as follows 
EmpModel.cs
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; }  
  
  }  
In the above model class we have added some validation on properties with the help of Data Annotations.
Step 3:
  Create Controller.
Now let us add the MVC 5 controller as in the following screenshot:


After clicking on Add button it will show the following window. Now specify the Controller name as Employee with suffix Controller it will add the empty controller class
Step 4 : Create Table and Stored procedures.
Now before creating the view let us create the table name Employee in database according to our model fields to store the details

Now create the stored procedures to insert employee details into database , The code snippet will be look like as following
Create procedure [dbo].[AddNewEmpDetails]  
(  
   @Name varchar (50),  
   @City varchar (50),  
   @Address varchar (50)  
)  
as  
begin  
   Insert into Employee values(@Name,@City,@Address)  
End  

Step 5 : Modify the EmployeeController.cs file.
Now open the EmployeeController.cs and create the action methods and database insert logic, after modifying the EmployeeController.cs class the the code snippet will be look like as follows
EmployeeController.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using CRUDUsingMVC.Models;
using System.Linq;
using System.Web.Mvc;
namespace UsingMVC
{

public class EmployeeController : Controller    
    {    
          

        private SqlConnection con;
        //To Handle connection related activities
        private void connection()
        {
            string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
            con = new SqlConnection(constr);

        }
          // GET: Employee/AddEmployee    
        public ActionResult AddEmployee()    
        {    
            return View();    
        }    
      
        // POST: Employee/AddEmployee    
        [HttpPost]    
        public ActionResult AddEmployee(EmpModel Emp)    
        {    
            try    
            {    
                if (ModelState.IsValid)    
                {    
                    EmpRepository EmpRepo = new EmpRepository();    
      
                    if (EmpRepo.AddEmployee(Emp))    
                    {    
                        ViewBag.Message = "Employee details added successfully";    
                    }    
                }    
                  
                return View();    
            }    
            catch    
            {    
                return View();    
            }    
        }    
      
      //To Add Employee details
        public bool AddEmployee(EmpModel obj)
        {

            connection();
            SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Name", obj.Name);
            com.Parameters.AddWithValue("@City", obj.City);
            com.Parameters.AddWithValue("@Address", obj.Address);        
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {

                return true;

            }
            else
            {

                return false;
            }
        }
              
    } 
}       

Step 6: Create strongly typed view.
To create the View to add Employees, right click on ActionResult method and then click Add view. Now specify the view name, template name and model class in EmpModel.cs and click on Add button, It will create the view named AddEmployee.cshtml, now open the AddEmployee.cshtml and modify the code as per our model class properties
 AddEmployee.cshtml
@model UsingMVC.Models.EmpModel  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
    <div class="form-horizontal">  
        <h4>Add Employee</h4>  
        <div>  
            @Html.ActionLink("Back to Employee List", "GetAllEmpDetails")  
        </div>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Save" class="btn btn-default" />  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10" style="color:green">  
                @ViewBag.Message  
  
            </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 7 - Run the Application
After running the application type the appropriate values into the textboxes and click on save button it will insert the records into the database as shown in the following image
From the preceding examples we have learned how to insert data into database in ASP.NET MVC using ADO.NET.
Note:
  • Configure the database connection in the web.config file depending on your database server location.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills
  • This application is created completely focusing on beginners.
Summary
I hope, this article is useful for all the readers. If you have any suggestions, please contact me.
Don't Forget To 

ViewBag ViewData and TempData in ASP.NET MVC

In web application maintaining the state of the application is very important to pass the data between the requests, ASP.NET uses lots of techniques to pass data between requests in which most of the techniques uses the Viewstate which slows the page load time, So in this article we will learn about ASP.NET MVC ViewBag, ViewData and TempData which is used in ASP.NET MVC application to pass data between the requests which not using Viewstate, Lets learn about them in short description with example which will understandable for beginners as wel as students .

What is ViewBag?

ViewBag is used to pass data from controller to view for single request.


Key points
  • Used to pass data from controller to view. 
  • The value assigned to ViewBag is only available for single request, if redirection happens then value will be null.
  • It is dynamic property of ControllerBase class which internally uses System.Dynamic.ExpandoObject() .
  • Its uses dynamic data type to hold data which was introduced in C# 4.0.
  •  Since it uses dynamic data type so it’s does not require type conversion such as int to string or string to int etc .
Example
Write the following code into your controller class
//Assigning value to viewBag
ViewBag.msg="Vithal Wadje";
In the above code ViewBag is the keyword and msg is the dynamic property . you can assign any property like msg because this is not predefined you need to assign as per your wish .
Accessing ViewBag value in View
<div>
@ViewBag.msg
</div>

In the above way we can access the ViewBag value into the view, I hope from all preceding example you have learned about the ViewBag.
    What is ViewData?

    ViewData is used to pass data from controller to view for single request which holds the data in key-value pairs were key will be string type and value is object type.


    Key points
    • Used to pass data from controller to view. 
    • ViewData is the object of ViewDataDictionary class which holds the data by key and value pair. 
    • In ViewData Key is the string type and value is the object type .
    • We need to handle null otherwise if ViewData value is null and we tried to access value then it throws the exception.
    • The value assigned to ViewData is only available for single request, if redirection happens then value will be null.
    • It is  property of ControllerBase class.
    •  It’s  require type conversion such as int to string or string to int etc .
    Example
    There are two ways to declare or assign the value to the ViewData which are as follows
    Write the following code into your controller class
    Method :1
    //Assigning value to ViewData
     ViewData["City"] = "Mumbai";
    In the above code City is the key and Mumbai is the value for ViewData object.
    Accessing ViewData value in View
    <div>
    @ViewData["City"]
    </div>
    In the above way we can access the ViewData value into the view.
    Method :2
    //Assigning value to ViewData
      ViewData.Add("Name", "Vithal Wadje");
    In the above code City is the key and Mumbai is the value for ViewData object.
    Accessing ViewData value in View
    <div>
    @ViewData["Name"]
    </div>
    In the above way we can access the ViewData value into the view, I hope from preceding example you have learned about ViewData
    What is TempData ? 

    TempData is used to pass data from controller to controller and also controller to view for current request.
    TempData in ASP.NET MVC by compilemode.com


    In Web application passing data from one request to another request is very important to perform the some action on data. In traditional ASP.NET application data passed to the session is stay's long time time in memory as per session timeout defined in the web.config file, But sometime we need to maintain data only for current request instead of all requests and data should be disappears in second request , for this situation session is not fit which maintain the data for all request so we need to use TempData to maintain data for only current request which saves the server memory by releasing the data when second request fires.I hope you understand when to use TempData over session variable.
    Key points
    • Used to pass data from controller to controller as well as controller to view.
    • It holds the Data for short time means till current request.
    • TempData internally uses session variable to hold the values during request.
    • TempData is the object of ViewDataDictionary class.
    • We need to handle null otherwise if  TempData value is null and we tried to access value then it throws the exception.
    • The value assigned to TempData is only available for single request, if again new request initiated then value will become null.
    • It is  property of ControllerBase class.
    •  It’s  require type conversion such as int to string or string to int etc . 
    Example
    We can assign the value to the TempData in the following way
    //Assigning value to TempData
     TempData["CityName"] = "Latur";
    In the above code CityName is the key and Latur is the value for TempData object.
    Accessing TempData value in View
    <div>
    @TempData["CityName"]
    </div>
    In the above way we can access the TempData value into the view.
    Accessing TempData value in Controller Action method
        public ActionResult CheckTempValue()
            {
               //Reading the values of TempData
                var TempName = TempData["EmpName"].ToString();
                return View();
            }
    In the above way we can access the TempData value into the controller, I hope from preceding example you have learned about the TempData.
    Summary
    I hope this article is useful for all readers to learn and know about the ViewBag, ViewData and TempData . If you have an any suggestion related to this article then please contact me.

    Don't Forget To 

    Display Data From Hosted Web API REST Service in ASP.NET MVC Using HttpClient

    Many reader asking me to write on how to get data from remotely hosted web API REST service , So I have decided to write this article to explain step by step how to display data from hosted web API REST Service in ASP.NET MVC using HttpClient. To demonstrate this lets create simple ASP.NET MVC application
    If are new and wants to learn web API REST service from creating to hosting to consuming in client application.
    In this article, we will use the same hosted Web API REST service  to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in ASP.NET MVC application step by step.
    Step 1 - Create MVC Application.
    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.
    3. After clicking, the following Window will appear. Choose empty project template and check on MVC option.

    The preceding step creates the simple empty ASP.NET MVC application without Model, View, and Controller, The Solution Explorer of created web application will look like the following.


    Step 2 - Install HttpClient library from NuGet

    We are going to use HttpClient to consume the Web API REST Service, so we need to install this library from NuGet Package Manager .
    What is HttpClient ?
    HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.
    To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.

    Step 3 - Install WebAPI.Client library from NuGet
    This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.
    Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.
    Step 4 - Create Model Class 
    Now, let us create the Model class named Employee.cs  or as you wish, by right clicking on Models folder with same number of entities which are exposing by our hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like this.
        public class Employee  
        {  
            public int Id { get; set; }  
            public string Name { get; set; }  
                     
            public string City { get; set; }  
          
        }   
    
    
    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 in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . Our hosted Web API REST Service includes these two methods, as given below.
    • GetAllEmployees (GET )
    • GetEmployeeById (POST ) which takes id as input parameter 
    The url of the hosted web API REST Service is  http://192.168.95.1:5555/api/Employee/GetAllEmployees

    In the preceding url
    • http://localhost:56290 Is the base address of web API service, It can be different as per your server.
    • api It is the used to differentiate between Web API controller and MVC controller request .
    • Employee This is the Web API controller name.
    • GetAllEmployees This is the Web API method which returns the all employee list.
    After modifying the code of Homecontroller class, the code will look like the following.
    Homecontroller.cs
    using ConsumingWebAapiRESTinMVC.Models;  
    using Newtonsoft.Json;  
    using System;  
    using System.Collections.Generic;  
    using System.Net.Http;  
    using System.Net.Http.Headers;  
    using System.Threading.Tasks;  
    using System.Web.Mvc;  
      
    namespace ConsumingWebAapiRESTinMVC.Controllers  
    {  
        public class HomeController : Controller  
        {  
            //Hosted web API REST Service base url  
            string Baseurl = "http://192.168.95.1:5555/";      
            public async Task<ActionResult> Index()  
            {  
                List<Employee> EmpInfo = new List<Employee>();  
                  
                using (var client = new HttpClient())  
                {  
                    //Passing service base url  
                    client.BaseAddress = new Uri(Baseurl);  
      
                    client.DefaultRequestHeaders.Clear();  
                    //Define request data format  
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
                      
                    //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                    HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");  
      
                    //Checking the response is successful or not which is sent using HttpClient  
                    if (Res.IsSuccessStatusCode)  
                    {  
                        //Storing the response details recieved from web api   
                        var EmpResponse = Res.Content.ReadAsStringAsync().Result;  
      
                        //Deserializing the response recieved from web api and storing into the Employee list  
                        EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);  
      
                    }  
                    //returning the employee list to view  
                    return View(EmpInfo);  
                }  
            }  
        }  
    }  

    I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient .
    Step 6 - Create strongly typed View
    Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.


    Now, click on "Add" button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.

    Index.cshtml 
    @model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    <div class="form-horizontal">  
      
        <hr />  
        <div class="form-group">  
      
      
            <table class="table table-responsive" style="width:400px">  
                <tr>  
                    <th>  
                        @Html.DisplayNameFor(model => model.Name)  
                    </th>  
                    <th>  
                        @Html.DisplayNameFor(model => model.City)  
                    </th>  
                      
                </tr>  
      
                @foreach (var item in Model) {  
                    <tr>  
                        <td>  
                            @Html.DisplayFor(modelItem => item.Name)  
                        </td>  
                        <td>  
                            @Html.DisplayFor(modelItem => item.City)  
                        </td>  
                          
                    </tr>  
    }  
      
            </table>  
        </div>  
    </div>  

    The preceding View will display all employees list . Now, we have done all the coding.
    Step 7 - Run the Application
    After running the Application, the employee list from hosted web API REST service will look like this.


    I hope, from the above examples, you have learned how to consume Web API REST Service in ASP.NET MVC using HttpClient.

    Note
    • This article is just guideline on how to consume Web API REST Service in ASP.NET MVC application using HttpClient .
    • In this article, the optimization is not covered in depth; do it as per your skills.
    Summary
    I hope, this article is useful for all the readers. If you have any suggestions, please contact me.
    Don't Forget To 

    Recap of My Speaking at National University of Singapore on Microsoft Azure IaaS Using ASP.NET Core

    I was recently visited to National University of Singapore on ‎January ‎07- 2017, NUS has very huge and world class campus with latest infrastructure, It was great pleasure to meet world class students from all over the world , Many students came up with great start up ideas and to boost their start up ideas I have extended my support to help them at free of cost to turn their ideas into reality .

    I was got opportunity to explain How Microsoft Azure helps startups to manage their application with less infrastructure cost without buying physical servers , I have explained real time example of Microsoft azure with ASP.NET Core


    Addressing group of students on Microsoft Azure Infrastructure as service (IaaS) using ASP.NET Core




     Following is the group photo with few students who led the event


    It was great and proud moment for me thanks to all my readers and community for great support. If you wants to invite to me to your any technical or career guidance related college event then you can contact me anytime , for my latest speaking visit Vithal Wadje Speaking  section
    Don't Forget To 

    Uploading Downloading PDF Files From DataBase In ASP.NET MVC

    Many times, we need to work with the file and storing the physical files on the Server, which is very difficult because it will consume lots of physical hard disc space of the Server. Thus, in this article, we will learn, how to upload and download the files directly from the database in ASP.NET MVC. Thus, let's learn step by step so the beginners can also understand.
    Step 1 - Create 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 in EmpModel.cs class and FileDetailsModel as:
    The code snippet of EmpModel.cs and FileDetailsModel .cs will look like-
    public class EmpModel  
       {  
           [Required]  
           [DataType(DataType.Upload)]  
           [Display(Name ="Select File")]  
           public HttpPostedFileBase files { get; set; }  
       }  
      
       public class FileDetailsModel  
       {  
           public int Id { get; set; }  
           [Display(Name = "Uploaded File")]  
           public String FileName { get; set; }  
           public byte[] FileContent { get; set; }  
      
      
       }  
    Step 3 - Create Table and Stored Procedure
    Now, create the stored procedure and the table to store the uploaded files in binary format and display back to the user's view. Use the script, given below, to create the 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 the preceding table script, we have created three columns Id, which is to identify the files unique key. FileName to store uploaded file name and FileContent to store the uploaded file contents in the binary format.
    Create the stored procedure to insert the file details, using the script, given below-
    Create Procedure [dbo].[AddFileDetails]  
    (  
    @FileName varchar(60),  
    @FileContent varBinary(Max)  
    )  
    as  
    begin  
    Set NoCount on  
    Insert into FileDetails values(@FileName,@FileContent)  
      
    End  
    To get the uploaded file details, use the code, given below-
    CREATE Procedure [dbo].[GetFileDetails]  
    (  
    @Id int=null  
      
      
    )  
    as  
    begin  
      
    select Id,FileName,FileContent from FileDetails  
    where Id=isnull(@Id,Id)  
    End  
    We have created the tables and stored procedures. I hope, you have created the same.
    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 in 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  
            {  
                 
                #region Upload Download file  
                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();  
          
                    }  
                     
                }  
                 
                [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 related operations  
                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();  
          
          
                }  
                #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 and download PDF files from the 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 two strongly typed views; one is to upload the files by choosing EmpModel.cs class  and Partial View by choosing FileDetailsModel class to display the uploaded files. The code snippet of the view looks like-

    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 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 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 and display back to the view is as follows-

    Now, see the image, given below, of the table, which shows how the preceding uploaded file data is stored as-
    From the preceding image, its clear that our uploaded file is stored into the database in the binary format. Now, click download button and it will show the following popup as-
    Now, choose, whether to open the file or save the file according to your convenience. After opening the file, it will show the following contents, based on the uploaded file as-

    I hope, from the preceding examples, you have learned, how to upload and download PDF files from the database In ASP.NET MVC, using FileResult.   
    Note
    • 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.
    Don't Forget To 

    Downloading Files From DataBase in 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 

    Display Country List Without Database in ASP.NET MVC

    When we need country name list to be use in an our application to serve the particular requirement we prefer to buy country database or web service or if cost issue then we prefer to create country name database manually but we don't require to follow these lengthy process since C# globalization class is capable to display the country list around 144 which is enough if requirement is not to capture all country names which are available in the world.
    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 

    Multiple Layout Pages In ASP.NET MVC

    Layout page shares the common design across all pages. It is similar to master page in ASP.NET. There are many methods which are listed below to change the layout page dynamically in ASP.NET MVC  
    • While Adding View Page, Assign Layout Page .
    • Using View Start Page
    I hope you have understand about the Layout page from preceding brief summary. Now let's implement it practically.
    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 user and admin controller controller. Right click on Controller folder in the created MVC application and add the controller class as.

     Now after selecting controller template, click on add button then the following window appears,
     
    Now specify the controller name and click on add button then the UserController class will be added into the application , now follow the same steps and add the AdminController class,
    After adding the two controller the solution explorer will be like the following,
     
    The preceding two controller classes are added into the project which are User and Admin and create the following action methods in respective controller class.
    UserController.cs
    public class UserController : Controller  
        {  
            public ActionResult Login()  
            {  
                //write logic here  
                return View();  
            }  
        } 
    AdminController.cs
    public class AdminController : Controller  
       {  
           [HttpPost]  
           public ActionResult AddRole()  
           {  
               //write logic here  
               return View();  
           }  
       } 
    For preceding two controllers we will use two different layout pages.
    Step 3: Add Views and Layout pages
    We can decide which layout page to be used while adding the view. IIt is same as deciding master page while adding ASP.NET web page. Let us follow the following steps to add layout page with view.
    Click on View folder of created MVC application as,

    As shown in preceding image, specify view name and check on use layout page option and click on add button then the following default layout page will be added into the solution explorer as,
    The above is default layout page and will be added into the solution explorer. Now lets add another layout page named admin as in the following. Click on solution explorer and add layout page as,
    Now click on add button, then added layout pages will look like as follows,

    In the preceding image, two layout pages are added under shared folder which are AdminLayoutPage and Layout.
    Step 4: Set layout pages to view
    We have created view and layout pages. Now let us assign layout pages to the views. There are many ways to assign layout page to the view which are listed as in the following:
    • Using wizard
    • Using ViewStart page
    • Using view method
    Using wizard
    You can use wizard to set the layout page while adding the view, steps are as follows:
    • Right click on view folder and select view template as,

    Specify the view name and check on Use a layout page and click on browse button. The following window will appear,

    Now choose layout page from preceding available Layout pages and click on ok button. The layout page will  look like as follows,

    Now click on add button then layout page reference added into the view page as,
     
    So whenever you will add through wizard or manually the layout page reference need to be set in every view page where the layout page is needed.
    Using ViewStart page
    Adding reference of layout page in every page is very difficult and repetitive of code. Let us consider I have one controller which as twenty plus action method then each twenty views we need to add reference of layout page. Assume another requirement we need to set layout page according to condition basic or controller basic then we need to use viewstart page .
    So lets open the ViewStart.cshtm page and write the following code,
    @{  
        string CurrentName = Convert.ToString(HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"]);  
        dynamic Layout;  
        switch (CurrentName)  
        {  
            case "User":  
                Layout = "~/Views/Shared/_Layout.cshtml";  
                break;  
            default:  
                //Admin layout  
                Layout = "~/Views/Shared/_AdminLayoutPage.cshtml";  
                break;  
        }  
    }  
    Now run the application, the Login view will  look like as follows in which we have used Layout page,
    Now run AddRole view, Then the output will look like the following,
     
    I hope from all the preceding examples, you have learned about layout pages in ASP.NET MVC.
    Note:
    • Download the Zip file of the sample application for a better understanding.
    • Apply proper validation before using it in your project.
    Summary
    I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.

    www.CodeNirvana.in

    Protected by Copyscape Online Copyright Protection
    Copyright © Compile Mode