Creating CheckBox List In ASP.NET MVC

In this article, we will learn how to create strongly typed checkbox list in ASP.NET MVC application, let's learn step by step about it.

Step 1 : Create an ASP.NET  MVC Application.

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

Step 2 : Add Model class

Right click on model folder of created MVC application project and add  class named CheckBoxModel.cs.

CheckBoxModel.cs
public class CheckBoxModel
    {
        public int Value { get; set; }
        public string Text { get; set; }
        public bool IsChecked { get; set; }
    }
    public class CheckBoxList
    {
        public List<CheckBoxModel> CheckBoxItems { get; set; }
    }

Step 3 : Add Controller

Right click on Controllers folder of created MVC application and add Controller named HomeController.cs.

HomeController.cs
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //Creating object of CheckBoxList model class
            CheckBoxList ChkItems = new CheckBoxList();
            //Additng items to the list
            List<CheckBoxModel> ChkItem = new List<CheckBoxModel>()
            {
              new CheckBoxModel {Value=1,Text="ASP.NET",IsChecked=true },
              new CheckBoxModel {Value=1,Text="C#",IsChecked=false },
              new CheckBoxModel {Value=1,Text="MVC",IsChecked=false },
              new CheckBoxModel {Value=1,Text="Web API" ,IsChecked=false},
              new CheckBoxModel {Value=1,Text="SignalR",IsChecked=false },
              new CheckBoxModel {Value=1,Text="SQL" ,IsChecked=false},
            };
            //assigning records to the CheckBoxItems list 
            ChkItems.CheckBoxItems = ChkItem;
            return View(ChkItems);
           
        }

    }

 Step 4: Add View

Right click on View folder of created MVC application project and add empty view named Index.cshtml. Now open the Index.cshtml view and write the following code into the view
@model BindCheckBoxListInMVC.Models.CheckBoxList
@{
    ViewBag.Title = "www.compilemode.com";
}
<div class="form-horizontal">
    <h4>Select your favourite Subjects</h4>
        @foreach (var item in Model.CheckBoxItems)
        {
            <input id="chk@(item.Value)"
                   type="checkbox"
                   value="@item.Value" 
                   checked="@item.IsChecked" />
                @item.Text <br />
        }
       
</div>
Now everything is ready ,run the application then the check box list will be look like as follows.

From all above example we have learned how to create strongly typed checkbox list in ASP.NET MVC.

Summary

I hope this article is useful for all readers, if you have a suggestion then please contact me.

Don't Forget To  
Related articles

Post Data To Controller Using jQuery Ajax in ASP.NET MVC

In this article we will learn how to post data to a controller using jQuery Ajax in ASP.NET MVC. So let's demonstrate it by creating simple ASP.NET MVC application.

Step 1 : Create an ASP.NET MVC Application.

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

Right click on model folder of created MVC application project and add class named Empmodel.cs
Empmodel.cs
public class EmpModel
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Address { get; set; }
        
    }
 Step 2 : Add Controller
 HomeController.cs
public class HomeController : Controller
    {
        private SqlConnection con;
       
        // GET: Home
        public ActionResult AddEmployee()
        {
           
            return View();
        }
        //Post method to add details
        [HttpPost]
        public ActionResult AddEmployee(EmpModel obj)
        {
            AddDetails(obj);

            return View();
        }

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

        }
        //To add Records into database 
        private void AddDetails(EmpModel obj)
        {
            connection();
            SqlCommand com = new SqlCommand("AddEmp", 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();
            com.ExecuteNonQuery();
            con.Close();

        }
    }
 Step 3: Add View
Right click on View folder of created MVC application project and add empty view named AddEmployee.cshtml
 Step 4: Create Jquery Post method
Now open the AddEmployee.cshtml view and create the following JQuery Post method to call controller .
<script>
    $(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddEmployee", // Controller/View 
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery 
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }

            });

        });
    });

</script>
Note

To work with jQuery we need to reference of jQuery library.You can use following CDN jQuery library or you can use same file by downloading it as offline jQuery file.
Now after adding the library and form controls the AddEmployee.cshtml code will be look like as

@{
    ViewBag.Title = "www.compilemode.com";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddEmployee", // Controller/View 
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery 
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }

            });

        });
    });

</script>
<br /><br />
<fieldset>
    <div class="form-horizontal">
        <div class="editor-label">
            Name
        </div>
        <div class="editor-label">
            <input type="text" id="txtName" />
        </div>

        <div class="editor-label">
            Address
        </div>
        <div class="editor-label">
            <input type="text" id="txtAddress" />
        </div>

        <div class="editor-label">
            City
        </div>
        <div class="editor-label">
            <input type="text" id="txtcity" />
        </div>
        <div class="editor-label">
            <br />
            <input class="btn-default" type="button" id="btnSave" value="Save" />
        </div>
    </div>
</fieldset>
Now everything is ready ,run the application and enter the details into the following form.



After entering the details click on save button then the details will be get added into the database as








From all above example we have learned how to post data to a controller using jQuery Ajax in ASP.NET MVC.

Note
  • Do a proper validation such as date input values when implementing.
  • Make the changes in the web.config file depending on your server details for the connection string.
Summary
I hope this article is useful for all readers, if you have a suggestion then please contact me.

How To Host ASP.NET MVC Web Application on Local IIS

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

Move the published code on Hosting Server

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



Open IIS Manager

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

 

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

Add Website to host an ASP.NET MVC application

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


After clicking on "Add Website" option, it displays the following configuration window.


I hope you understood the preceding configuration by highlighted text.

Define Site Name & Application Pool

Define the site name which will be useful to uniquely identify the site within the IIS server. After specifying the site name, choose the application pool from available pools. You can even create a custom application pool with any desired name. Currently, our IIS manager has the following application Pools.

 

Choose the application pool depending on your application configuration. In this article, we are going to choose DefaultAppPool.

Browse and select Published Folder path

Now, choose the physical location of published code files by clicking on "Browse" button, as shown in the following image.


Now, click on "OK" button.

Define IP address & Port

Choose one IP address from the list of available IP addresses and define the unique port number for the application, which will be unique within the defined IP address.

Choose Protocol & Host name (optional )

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


Now, click on OK button. It will create and add the application in IIS.

Browse the application using web browser

Browse the hosted application using your system (PC/Laptop) browser , Click on browse hyperlink which is highlighted in the following image

 

After clicking on preceding IIS shown image browse hyperlink, then application will open in your default web browser as shown in the following image
 
 

Preceding is our IIS hosted ASP.NET MVC application which is running in browser.

Note
  • This article is just guideline to show how to host ASP.NET MVC web API application on IIS .
  • Optimize the speed by setting debug as false etc., from web.config file as per your skills.
  • In this article, the optimization is not covered in depth.
  • Configure the authentication in IIS as per your requirement . 

Summary

I hope, this article is useful for all the readers to learn about hosting an  ASP.NET MVC web application on local IIS. If you have any suggestions, please contact me.

Learn How to Create an ASP.NET MVC Application Step by Step

How To Call Action Method Using ActionLink in ASP.NET MVC

In this article we will learn how to call action method which resides in different controller in ASP.NET MVC, first we need to pass the following parameters in ActionLink are as follows, The following code snippet can be written in view or partial view.
@Html.ActionLink("Index", "ActionName", "ControllerName", null, new { id = "OT",
style = "color: white" })
In the above code
  •     Index is the ActionLink Name
  •     ActionName is the View name or ActionResult Name.
  •     ControllerName will be name of our controller .
After implementing the code in parent view, the entire code will be look like as follows

Parentview.Cshtml

@{
    ViewBag.Title = "Parentview";
}

<h2>Parentview</h2>
@*To call same same controller view*@
@Html.ActionLink("Index", "ActionName")

@*To call another controller view*@
@Html.ActionLink("Index", "ActionName", "ControllerName", null, new { id = "OT",
 style = "color: white" })
Summary
I hope the preceding explanation will help you to learn how to call cross controller action methods. If you have any suggestion then drop the comment in the comment box

Read Word File Using ASP.NET

Often there is a need to read word file contents, so by considering that requirement I decided to write the article. Let's  learn step-by-step how to read a word file and display its content in a Textbox.

 The most common scenarios are as follows:
  • To upload a resume and show the contents in a TextBox as summary.
  •  Save that resume contents into the database so later on it is useful for CV or resume parsing.
  • In a blog or community website to upload file contents directly into the editor so it becomes faster to edit contents and save it.
Now let us see the preceding explanation by creating a sample web application as follows:
  1. "Start" - "All Programs" - "Microsoft Visual Studio"
  2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
  3. Provide the web site a name such as "ReadWordFilesInFillTextBox" or another as you wish and specify the location.
  4. Then right-click on the Solution Explorer and select "Add New Item" and Add Web Form.
  5. Drag and drop two Buttons, a Fileuploader and TextBox control onto the <form> section of the Default.aspx page
  6. Set TextBox text mode to multiline.
Now the default.aspx page source code will looks as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>Article by Vithal Wadje</title>  
</head>  
<body bgcolor="navy">  
    <form id="form2" runat="server">  
    <div style="color: White;">  
        <h4>  
            Article for C#Corner  
        </h4>  
        <br />  
        <table width="100%">  
            <tr>  
                <td>  
                    <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" Height="142px" Width="380px"></asp:TextBox><br />  
                </td>  
            </tr>  
        </table>  
        <br />  
        <table>  
            <tr>  
                <td>  
                    <asp:FileUpload ID="FileUpload1" runat="server" />  
                </td>  
                <td>  
                    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />  
                </td>  
                <td>  
                    <asp:Button ID="Button1" runat="server" Text="Clear" OnClick="Button1_Click" />  
                </td>  
            </tr>  
        </table>  
    </div>  
    </form>  
</body>  
</html>  

Now add the reference for Microsoft.Office.Interop by right-clicking the Solution Explorer to handle the Word file related process. I hope you have done that. The following namespaces are required to work with operations related to Word files:

    using System.IO;  
    using Microsoft.Office.Interop.Word;  
    using System.Text; 

Now double-click on the upload button and write the following code:

    protected void btnUpload_Click(object sender, EventArgs e)  
       {  
           //createting the object of application class  
           Application Objword = new Application();  
      
           //creating the object of document class  
           Document objdoc = new Document();  
      
           //get the uploaded file full path  
           dynamic FilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);  
      
           //pass the optional (missing) parameter to API  
           dynamic NA = System.Type.Missing;  
      
           //open Word file document   
    objdoc = Objword.Documents.Open  
                  (ref FilePath, ref NA, ref NA, ref NA, ref NA,  
                   ref NA, ref NA, ref NA, ref NA,  
                   ref NA, ref NA, ref NA, ref NA,  
                   ref NA, ref NA, ref NA  
                    
                   );  
                   
      
          //creating the object of string builder class  
           StringBuilder sb = new StringBuilder();  
      
           for (int Line = 0; Line < objdoc.Paragraphs.Count; Line++)  
           {  
               string Filedata = objdoc.Paragraphs[Line + 1].Range.Text.Trim();  
      
               if (Filedata != string.Empty)  
               {  
                   //Append word files data to stringbuilder  
                   sb.AppendLine(Filedata);  
               }  
                   
           }  
      
           //closing document object   
           ((_Document)objdoc).Close();  
      
           //Quit application object to end process  
           ((_Application)Objword).Quit();  
      
           //assign stringbuilder object to show text in textbox  
           TextBox1.Text =Convert.ToString(sb);  
       } 

Now double-click on the reset button and write the following code:

    protected void Button1_Click(object sender, EventArgs e)  
       {  
           TextBox1.Text =string.Empty;  
       } 

The entire code of the default.aspx.cs will look as in the following:

    using System;  
    using System.IO;  
    using Microsoft.Office.Interop.Word;  
    using System.Text;  
      
      
    public partial class _Default : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
      
        }  
        protected void btnUpload_Click(object sender, EventArgs e)  
        {  
            //createting the object of application class  
            Application Objword = new Application();  
      
            //creating the object of document class  
            Document objdoc = new Document();  
      
            //get the uploaded file full path  
            dynamic FilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);  
      
            //pass the optional (missing) parameter to API  
            dynamic NA = System.Type.Missing;  
      
            //open Word file document   
     objdoc = Objword.Documents.Open  
                   (ref FilePath, ref NA, ref NA, ref NA, ref NA,  
                    ref NA, ref NA, ref NA, ref NA,  
                    ref NA, ref NA, ref NA, ref NA,  
                    ref NA, ref NA, ref NA  
                     
                    );  
                    
      
           //creating the object of string builder class  
            StringBuilder sb = new StringBuilder();  
      
            for (int Line = 0; Line < objdoc.Paragraphs.Count; Line++)  
            {  
                string Filedata = objdoc.Paragraphs[Line + 1].Range.Text.Trim();  
      
                if (Filedata != string.Empty)  
                {  
                    //Append word files data to stringbuilder  
                    sb.AppendLine(Filedata);  
                }  
                    
            }  
      
            //closing document object   
            ((_Document)objdoc).Close();  
      
            //Quit application object to end process  
            ((_Application)Objword).Quit();  
      
            //assign stringbuilder object to show text in textbox  
            TextBox1.Text =Convert.ToString(sb);  
        }  
      
        protected void Button1_Click(object sender, EventArgs e)  
        {  
            TextBox1.Text =string.Empty;  
        }  
    } 


Now run the application. The UI will look as follows:




In the preceding UI Browse control will be used to select the files from the physical location. On a upload button click, it will read the uploaded Word file and show it in the TextBox. The Clear button will clear the text box contents.

Now select the Word file and click on upload, it will show the file contents in the TextBox as follows.
  


Now you have seen how to read Word file contents and put it into a TextBox.

Notes
  • Do a proper validation such as if it has a file or not of the File Upload control when implementing.
Summar

I hope this article is useful for all readers, if you have a suggestion then please contact me.

Download Binary Data From SQL Using ASP.NET MVC

This articles explains how to download binary data from SQL database using ASP.NET MVC, please read my previous article which shows how to upload files into the database in binary format.
Let's consider we have following SQL table having the binary format data.


Now let's create the front end application step by step using ASP.NET MVC to download the files 

Step 1: Create an ASP.NET 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. After clicking, the following Window will appear:


Step 2: 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 3 : 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  

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 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 5:  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> 


Step 6 - 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.

    Get Data in ASP.NET MVC Using Web API

    This article  explains step by step how to get data in ASP.NET MVC using web api. To demonstrate this lets create simple ASP.NET MVC application before it if you 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 ASP.NET MVC Application.

    1. "Start", followed by "All Programs" and select "Microsoft Visual Studio".
    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, 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 as follows

        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 get data in ASP.NET MVC using web api

    Note
    • 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 to learn about getting data from web api in ASP.NET MVC. If you have any suggestions, please contact me. 

    Show Confirm Alert Box

    Before deleting records we need show confirm alert box to ensure something should not delete or edit the records accidently. Let us consider following html table which 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.

    Strongly Typed Checkbox List in ASP.NET MVC

    This article will demonstrate how to create strongly typed checkbox list in an ASP.NET MVC application. So let's learn step by step.

    Step 1 : Create an ASP.NET MVC Application.

    Now let us start with a step by step approach from the creation of simple MVC application as in the following:
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK . 
     Step 2 : Add Model class
    Right click on model folder of created MVC application project and add  class named CheckBoxModel.cs
    CheckBoxModel.cs
    public class CheckBoxModel
        {
            public int Value { get; set; }
            public string Text { get; set; }
            public bool IsChecked { get; set; }
        }
        public class CheckBoxList
        {
            public List<CheckBoxModel> CheckBoxItems { get; set; }
        }
     Step 2 : Add Controller
    Right click on Controllers folder of created MVC application and add Controller named HomeController.cs
     HomeController.cs
    public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                //Creating object of CheckBoxList model class
                CheckBoxList ChkItems = new CheckBoxList();
                //Additng items to the list
                List<CheckBoxModel> ChkItem = new List<CheckBoxModel>()
                {
                  new CheckBoxModel {Value=1,Text="ASP.NET",IsChecked=true },
                  new CheckBoxModel {Value=1,Text="C#",IsChecked=false },
                  new CheckBoxModel {Value=1,Text="MVC",IsChecked=false },
                  new CheckBoxModel {Value=1,Text="Web API" ,IsChecked=false},
                  new CheckBoxModel {Value=1,Text="SignalR",IsChecked=false },
                  new CheckBoxModel {Value=1,Text="SQL" ,IsChecked=false},
                };
                //assigning records to the CheckBoxItems list 
                ChkItems.CheckBoxItems = ChkItem;
                return View(ChkItems);
               
            }
    
        }
     Step 3: Add View
    Right click on View folder of created MVC application project and add empty view named Index.cshtml. Now open the Index.cshtml view and write the following code into the view
    @model BindCheckBoxListInMVC.Models.CheckBoxList
    @{
        ViewBag.Title = "www.compilemode.com";
    }
    <div class="form-horizontal">
        <h4>Select your favourite Subjects</h4>
            @foreach (var item in Model.CheckBoxItems)
            {
                <input id="chk@(item.Value)"
                       type="checkbox"
                       value="@item.Value" 
                       checked="@item.IsChecked" />
                    @item.Text <br />
            }
           
    </div>
    Now everything is ready ,run the application then the check box list will be look like as follows .
    From all above example, we have learned how to create strongly typed checkbox list in ASP.NET MVC.
    Summary

    I hope this article is useful for all readers, if you have a suggestion then please contact me.

    Don't Forget To  
    Related articles

    www.CodeNirvana.in

    Protected by Copyscape
    Copyright © Compilemode