How To Show Confirm Alert Box on ActionLink Click in ASP.NET MVC

Many times we need show confirm alert box while deleting ,saving and editing information in MVC application .The beauty of MVC is pure html and we can bind records using HTML table tag , Before deleting any records we need to show the confirm box , So let's see how we can achieve it without writing javascript or JQuery code .
Let us consider following html table has list of records
<table class="table">
 <tr>
 <th>

            @Html.DisplayNameFor(model => model.Name)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.City)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Address)

        </th>

        <th></th>

    </tr>

    @foreach (var item in Model)

    {

        @Html.HiddenFor(model => item.Empid)

        <tr>

           <td>

                @Html.DisplayFor(modelItem => item.Name)

            </td>

            <td>

                @Html.DisplayFor(modelItem => item.City)

            </td>

            <td>

                @Html.DisplayFor(modelItem => item.Address)

            </td>

            <td>

              @Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) |

 

                @Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }

               )

         </td>

        </tr>

    }
</table>
Now to show alert box just modify the ActionLink in view are as follows
@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid },
new { onclick = "return confirm('Are sure wants to delete?');" })
In the above ActionLink
  • Delete is the ActionLink Name.  
  • DeleteEmp is the ActionResult name .
  • EmpId is the unquie id from which specific records are deleted. 
After clicking on delete button the alert box will be shown are as follows

I hope from all preceding examples , You have learned how to show alert box Action Link click in ASP.NET MVC.
Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me.

Past User Group Speaking : Introduction To ASP.NET Core


Speaking in C# Corner Mumbai Chapter event which is led by me on ASP.NET Core , If you wants to learn about ASP.NET core then join my interactive session on ASP.NET core.

Agenda

 Date : 15-10-2016

Vithal Wadje speaking on ASP.NET Core




Introduction to ASP.NET Core

  • What is ASP.NET Core ?
  • What is .NET Core ?
  • Difference between .NET framework and .NET core Framework.
  • Difference between ASP.NET and ASP.NET core.
  • Building ASP.NET Core application .
  • Understanding the Folder structure of ASP.NET core.
  • Understanding Routing in ASP.NET core
  • What is wwwroot folder ?
  • What is Project.json ?
  • What is global.json
  • What is appsettings.json ?
  • Hosting ASP.NET core application on linux OS .
  • Q & A.


    Where:

    IBSAR Institute of Management and Studies 
    Sanjay Nagar, Karjat West
    Karjat Maharashtra INDIA


    Price: Free of cost

    Requirement: Optional to bring your laptop and internet card.

    Date : 15-10-2016
    Time : 10 AM To 4:30 PM

                                  Registration Closed


    How To Send Emails In ASP.NET MVC

    Email communication is very important in today's modern applications, and there are many ways to send emails through applications to users. I wrote a series of articles on email sending in ASP.NET, which was a very successful series in terms of views and downloads. Now in this article we will learn how to send emails directly from the razor view in ASP.NET MVC with the help of the WebMail helper class . So let's learn step by step, so beginners can also learn how to send emails in ASP.NET MVC.

    What is WebMail Helper Class?

    WebMail is the static class which is used to send emails directly from Razor View as well as the controller class in ASP.NET MVC .

    Prerequisites
    • Active internet connection.
    • Email id of any provider such as Gmail, Yahoo or your organization to send emails. 
    Now let's create a simple MVC application to demonstrate this.

    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:
     
    3. 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 whose Solution Explorer will look like the following:


    Step 2: Create Model Class


    Now let us create the model class named EmployeeModel.cs by right-clicking on the model folder as in the following screenshot:

     

    Note:

    It is not mandatory that the Model class be in the Model 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 names, or in a separate class library.

    EmployeeModel.cs class code snippet:
    using System.ComponentModel.DataAnnotations;  
      
    namespace SendingEmailsWithWebMailInMVC.Models  
    {  
        public class EmployeeModel  
        {          
             
            [DataType(DataType.EmailAddress),Display(Name ="To")]  
            [Required]  
            public string ToEmail { get; set; }  
            [Display(Name ="Body")]  
            [DataType(DataType.MultilineText)]  
            public string EMailBody { get; set; }  
            [Display(Name ="Subject")]  
            public string EmailSubject { get; set; }  
            [DataType(DataType.EmailAddress)]  
            [Display(Name ="CC")]  
            public string EmailCC { get; set; }  
            [DataType(DataType.EmailAddress)]  
            [Display(Name ="BCC")]  
            public string EmailBCC { get; set; }  
        }  
    }  

    Step 3 : Add Controller Class


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

     
    After clicking on Add button it will show the window. specify the Controller name as Home with suffix Controller.

    Note:

    The controller name must have a suffix of 'Controller' after specifying the name of the controller. Now the default code in HomeController.cs will look like as follows:

    HomeController.cs
    using System.Web.Mvc;  
    namespace SendingEmailsWithWebMailInMVC.Controllers  
    {  
        public class HomeController : Controller  
        {  
            // GET: Index view  
            public ActionResult Index()  
            {             
                return View();  
            }  
      
            [HttpPost]  
              
            public ActionResult SendEmailView()  
            {  
                //call SendEmailView view to invoke webmail  
                return View();  
            }  
        }  
    }  

    Step 4 : Creating strongly typed view named Index using employee model and SendEmailView 

    Right click on the View folder of the created application and choose Add View. Select employee model class and scaffolding to create a view to send emails.

     
    Now open the Index.cshtml view. Then follow the default code, which you will see is generated by
    The MVC scaffolding template as,

    Index.cshtml
    @model SendingEmailsWithWebMailInMVC.Models.EmployeeModel  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
    @*Send request to invoke SendEmailView view*@  
    @using (Html.BeginForm("SendEmailView","Home",FormMethod.Post))   
    {  
        @Html.AntiForgeryToken()  
        <div class="form-horizontal">      
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            <div class="form-group">  
                @Html.LabelFor(model => model.ToEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.ToEmail, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.EMailBody, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EMailBody, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EmailSubject, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.EmailCC, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EmailCC, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                @Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EmailBCC, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            <div class="form-group">  
                <div class="col-md-offset-2 col-md-10">  
                    <input type="submit" value="Send" class="btn btn-default" />  
                </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>  
    The preceding view is used to Get the Input email details from users , Now create the view named SendEmailView to configure the emails using WebMail class.
    SendEmailView.cshtml

    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
      @{  
          try  
          {  
              //parameters to send email  
              string ToEmail, FromOrSenderEmail = "YourGamilId@gmail.com", SubJect, Body, cc, Bcc;  
      
              //Reading values from form collection (Querystring) and assigning values to parameters  
              ToEmail = Request["ToEmail"].ToString();  
              SubJect = Request["EmailSubject"].ToString();  
              Body = Request["EMailBody"].ToString();  
              cc = Request["EmailCC"].ToString();  
              Bcc = Request["EmailBCC"].ToString();  
              //Configuring webMail class to send emails  
              WebMail.SmtpServer = "smtp.gmail.com"; //gmail smtp server  
              WebMail.SmtpPort = 587; //gmail port to send emails  
              WebMail.SmtpUseDefaultCredentials = true;  
              WebMail.EnableSsl = true; //sending emails with secure protocol  
              WebMail.UserName = FromOrSenderEmail;//EmailId used to send emails from application  
              WebMail.Password = "YourGmailPassword";  
              WebMail.From = FromOrSenderEmail; //email sender email address.  
      
              //Sending email  
              WebMail.Send(to: ToEmail, subject: SubJect, body: Body, cc: cc, bcc: Bcc, isBodyHtml: true);  
            <hr />  
            <div class="text-success">  
                Email Sent Successfully.  
            </div>  
          }  
          catch (Exception)  
          {  
            <div class="text-danger">  
                Problem while sending email, please check gmail server details.  
            </div>  
          }  
    }  
    Now after adding the model , view and controller our application solution explorer will look as follows,


    Now we have done all coding to send emails using WebMail class.

    Step 5 : Now run the application.


    After running the application initial screen will look as follows,


    The preceding view is used to send the emails. Now click on the send button without entering To email address and an invalid cc and bcc email address, it throws the following errors .

     
    Now Enter the valid details as follows,


    After clicking on the Send button, it will redirect to the SendEmailView, which invokes the WebEmail class and sends the email. After successfully sending the email, the following message will be shown.

    Now open your Gmail inbox and see the details which we have used to send the email as


    Now open the email. It will show the email content as follows.



    I hope from all the preceding examples we have learned how to send email using the WebMail helper class in ASP.NET MVC Razor view.

    Note:

    • 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.
    • You need an active internet connection to send the email .
    Summary

    I hope this article is useful for all readers. If you have any suggestions, please contact me.

    Read more articles on ASP.NET MVC:

    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

    DropDownList Using JSON Data In ASP.NET MVC

    In this article, we will learn how to bind the DropDownList using JSON data in ASP.NET MVC. Let's learn it step by step through creating a simple ASP.NET 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 ASP.NET MVC empty application option and click on OK

    Step 2: Add model class.

    Right click on model folder of created ASP.NET  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 ASP.NET 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 returns a view named Index and another one will return a json result named CityList. Remember that instead of going to the database I have created a list of records and returned it as json. However you can bind this list from the database, but in this example assume that this list is coming from the 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.

    Two Factor Authentication In ASP.NET MVC - Part 1

    This Video tutorial will introduce about two factor authentication in ASP.NET MVC which covers the following topics
    • What is Authentication?
    • Overview of Traditional authentication techniques.
    • Security threats of traditional authentication techniques.
    • What is two factor authentication?
    • Advantages of two factor authentication?
    • Two factor authentication providers
    • Registering for two factor authentication. 
    Now Lets 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

      Display JSON Data From Controller To View In ASP.NET MVC

      There are many ways to display data from controller to view and to  make easier to understand students as well as beginners I have decided to write series of articles on ways to display data from controller to view , hence in this first article of series we will learn how to display JSON (JavaScript Object Notation ) data from controller to view in ASP.NET MVC.
      Let's start step by step by creating one simple ASP.NET MVC application.

      Step 1 : Create 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 : Create Model Class
      Right click on Model folder in the created MVC application ,give the class name Employee or as you wish and click on OK .
      Employee.cs
      public class Employee
          {
              public int Id { get; set; }
              public string Name { get; set; }
              public string City { get; set; }
              public string  Address { 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 
      and click on OK
      HomeControlle.cs
      public class HomeController : Controller
          {
              // GET: Home
              public ActionResult Index()
              {
              return View();
              }
              [HttpGet]
              public JsonResult EmpDetails()
              {
              //Creating List
                  List<Employee> ObjEmp = new List<Employee>()
                  {
              //Adding records to list
              new Employee {Id=1,Name="Vithal Wadje",City="Latur",Address="Kabansangvi" },
              new Employee {Id=2,Name="Sudhir Wadje",City="Mumbai",Address="Kurla" }
                  };
              //return list as Json
              return Json(ObjEmp, JsonRequestBehavior.AllowGet);
              }
          }
      In the above controller class JsonResult method EmpDetails  we have added the records into the Generic list. and returning it as JSON  to avoid database query for same result.
      To work with JQuery we need a following JQuery library
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>
      The preceding JQuery library file version may be different that is lower or higher
      Step 4 : Add Partial view
      Right click on Home folder inside the View folder in the created MVC application as

      Give the name EmpDetails and click on Add button and write the following code.
      <script src="~/Scripts/jquery-1.10.2.min.js"></script>
      <script>
          $(document).ready(function () {
              //Call EmpDetails jsonResult Method
              $.getJSON("Home/EmpDetails",
              function (json) {
              var tr;
              //Append each row to html table
              for (var i = 0; i < json.length; i++) {
                      tr = $('<tr/>');
                      tr.append("<td>" + json[i].Id + "</td>");
                      tr.append("<td>" + json[i].Name + "</td>");
                      tr.append("<td>" + json[i].City + "</td>");
                      tr.append("<td>" + json[i].Address + "</td>");
                      $('table').append(tr);
                  }
              });
          });
      </script>
      <table class="table table-bordered table-condensed table-hover table-striped">
              <thead>
              <tr>
              <th>Id</th>
              <th>Name</th>
              <th>City</th>
              <th>Address</th>
              </tr>
              </thead>
              <tbody></tbody>
      </table>
      

      Step 5 : Call partial view EmpDetails in Main Index view
      Now call the partial view EmpDetails in Main Index view as using following code
      @{
          ViewBag.Title = "www.compilemode.com";
      }
      <div style="margin-top:20px">
      @Html.Partial("EmpDetails");
      </div>
      
      Step 6 : Run the application


      I hope from preceding examples , You have learned how to display JSON data from controller to view in ASP.NET MVC.
      Summary
      I hope this tutorial is useful for all readers. If you have any suggestion then please comment below to the article.

      www.CodeNirvana.in

      Protected by Copyscape
      Copyright © Compilemode