Reader Level:
ARTICLE

Display Data in ASP.NET Web API MVC 4 View

Posted by Gaurav Gupta Articles | ASP.NET MVC July 27, 2012
In this article we are going to learn how to create an ASP.NET Web API and also show data in a MVC view.
  • 2
  • 0
  • 64883

Today we will learn MVC 4 in ASP.NET. In this artilce I will create a simple ASP.NET Web API Using MVC 4.

First we have to create a table in SQL Server for the data we will fetch. So, create a table with some records. That step is for you to do.

We will create a simple ASP.NET MVC 4 Web API that displays the data using View. We have to create the following things:

A Controller.
A Model.
A View.

Any user request first comes to the controller class; the controller class then invokes the model and attaches the model to the view for display to the end user.

Now, let's starts to create a ASP.NET Web API using MVC 4.

Step 1: Open the Visual Studio 2013 RC.

  • Go to Visual C# -> File menu-> New -> Project.
  • Then, Select Web from the left pane.
  • Select ASP.NET MVC 4 Web Application.
  • Rename it as you want.
  • Click the Ok button.

3.png

4.png

Step 2:
Now, we are going to add a model class that contains the data in your application:

  • In Solution Explorer, right-click the Models folder.
  • Select Add, then select Class.
  • Name the class "Employee".
  • Click the Add button after that.

3.png

Step 3: Now, we will create a class in the Employee.cs file that contains some properties related to the database fields; it is:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace WebApi.Models

{

    public class product

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string desig { get; set; }

        public decimal salary { get; set; }

    }

}

Step 4: So let's go and add a new controller as shown in the following figure. Select MVC Empty Controller from the drop down list:

9.png

10.png

Step 5: Once you add the new controller you should see some kind of code snippet as shown in the following snippet:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Data;

using System.Data.SqlClient;

using WebApi.Models;

 

namespace WebApi.Controllers

{

    public class empController : Controller

    {

        //

        // GET: /emp/

        private List<product> products = new List<product>();

        private int _nextId = 1;

        SqlConnection con;

        SqlDataAdapter da;

        DataSet ds = new DataSet();

 

        public ActionResult Index()

        {

            con = new SqlConnection("Data Source=MYPC;Initial Catalog=MyDb;uid=sa;pwd=wintellect");

            da = new SqlDataAdapter("select * from Employee", con);

            da.Fill(ds);

    foreach (DataRow dr in ds.Tables[0].Rows)

            {

                products.Add(new product() { Id = int.Parse(dr[0].ToString()), Name = dr[1].ToString(), desig = dr[2].ToString(), salary = int.Parse(dr[3].ToString()) });

            }          

            return View(products);

        }

    }

}

In the above code the controller has a method that retreives the data from the database and makes obects of the class employee then stores these objects into a collection object. After creating an object the collection is returned to the view to display it.

Step 6: Now we need to add the view. So click on the Index function which is present in the control and click on the add view menu as shown in the following figure:

5.png

Step 7: This will show you a window. Set the view name as the method name and check "Create a strongly-typed view" and bind this view to the model class from the dropdown as shown in the following figure.

7.png

Step 8: After that you can access the properties of the model class using the model. The following is the view code which displays the Employee Details in tabular formats:
 

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<WebApi.Models.product>>" %>

 

<!DOCTYPE html>

<html>

<head runat="server">

    <meta name="viewport" content="width=device-width" />

    <title>List of All Employees</title>

</head>

<body bgcolor="red" align="center">

   <h2>List of Empolyees</h2>

    <table border="1"  height="200" width="400" align="center" bgcolor="pink">

        <tr>

            <th>

                <%: Html.DisplayNameFor(model => model.Name) %>       

            </th>

            <th>

                <%: Html.DisplayNameFor(model => model.desig) %>

            </th>

            <th>

                <%: Html.DisplayNameFor(model => model.salary) %>

            </th>

            <th></th>

        </tr>

   

    <% foreach (var item in Model) { %>

        <tr>

            <td>

                <%: Html.DisplayFor(modelItem => item.Name) %>            

            </td>

            <td>

                <%: Html.DisplayFor(modelItem => item.desig) %>

            </td>

            <td>

                <%: Html.DisplayFor(modelItem => item.salary) %>

            </td>

        </tr>

    <% } %>

    </table>

</body>

</html>


Step 9: In this step we need to set the routing properties so that when we run the application it will not give an error. We make our Controller as the Default Controller.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace WebApi

{

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "emp", action = "Index", id = UrlParameter.Optional }

            );

        }

    }

}

Step 10: Now, Build the application and press F5 to run the application.

11.png

COMMENT USING

Trending up