Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

.NETMVCVisual StudioWeb API
Home›.NET›Load Data From Database Using Web API

Load Data From Database Using Web API

By SibeeshVenu
October 31, 2015
6760
11
Share:
CRUD_in_MVC_Using_Web_API

In this article we will learn about Loading Data From Database in MVC using Web API. We will use Visual Studio 2015 to create a Web API and performs the operations. In this project we are going to create a database and a table called tbl_Subcribers which actually contains a list of data. We will use our normal jQuery ajax to call the Web API, once the data is ready we will format the same in an html table. I hope you will like this.

Download the source code

  • Load Data From Database Using Web API
  • Background

    What is a Web API?

    A Web API is a kind of a framework which makes building HTTP services easier than ever. It can be used almost everywhere including wide range of clients, mobile devices, browsers etc. It contains normal MVC features like Model, Controller, Actions, Routing etc. Support all HTTP verbs like POST, GET, DELETE, PUT.

    Why Web API

    Why Web API

    Image Courtesy : blogs.msdn.com

    Why Web API

    Why Web API

    Image Courtesy : forums.asp.net

    Using the code

    We will create our project in Visual Studio 2015. To create a project click File-> New-> Project.

    CRUD_in_MVC_Using_Web_API

    CRUD_in_MVC_Using_Web_API

    CRUD_in_MVC_Using_Web_API


    CRUD_in_MVC_Using_Web_API

    Create a control

    Now we will create a control in our project.

    CRUD_in_MVC_Using_Web_API_Adding_Control

    CRUD_in_MVC_Using_Web_API_Adding_Control

    Select Empty API Controller as template.

    CRUD_in_MVC_Using_Web_API_Select_APIControl

    CRUD_in_MVC_Using_Web_API_Select_APIControl

    As you can notice that we have selected Empty API Controller instead of selecting a normal controller. There are few difference between our normal controller and Empty API Controller.

    Controller VS Empty API Controller

    A controller normally render your views. But an API controller returns the data which is already serialized. A controller action returns JSON() by converting the data. You can get rid of this by using API controller.

    Find out more: Controller VS API Controller

    Create a model

    As you all know, we write logic in a class called model in MVC. So next step what we need to do is creating a model.

    Right click on Model and click Add new Items and then class. Name it as Subscribers. We are going to handle the subscriber list who all are subscribed to your website.

    Now we will create a Database to our application.

    Create Database

    CRUD_in_MVC_Using_Web_API_Create_Database

    CRUD_in_MVC_Using_Web_API_Create_Database

    Once you created the database, you can see your database in App_Data folder.

    CRUD_in_MVC_Using_Web_API_Created_DB

    CRUD_in_MVC_Using_Web_API_Created_DB

    Now will add a new table to our database.

    CRUD_in_MVC_Using_Web_API_Adding_Table

    CRUD_in_MVC_Using_Web_API_Adding_Table

    You can see the query to create a table below.

    [sql]
    CREATE TABLE [dbo].[Table]
    (
    [SubscriberID] INT NOT NULL PRIMARY KEY,
    [MailID] NVARCHAR(50) NOT NULL,
    [SubscribedDate] DATETIME2 NOT NULL
    )
    [/sql]

    It seems our database is ready now.

    Load Data From Database Using Web API

    Load Data From Database Using Web API

    The next thing we need to do is to create a ADO.NET Entity Data Model. SO shall we do that? Right click on your model and click on add new item, in the upcoming dialogue, select ADO.NET Entity Data Model.Name that file, Here I have given the name as SP. And in the next steps select the tables, stored procedures, and views you want.

    Load Data From Database Using Web API

    Load Data From Database Using Web API

    So a new file will be created in your model folder.

    Now we will create an ajax call so that you can call the web API. We will use normal Ajax with type GET since we need to just retrieve the data.

    A web API control does not return any action result or any json result, so we need to manually do this. We will use the index.cshtml file as our view

    We are going to call our web API as follows from the view Index.cshtml.

    [js]
    @section scripts
    {
    <script>
    $(document).ready(function () {
    $.ajax(
    {
    type: ‘GET’,
    dataType: ‘json’,
    contentType: ‘application/json;charset=utf-8’,
    url: ‘http://localhost:3064/api/Subscribers’,
    success: function (data) {
    try {
    debugger;
    var html = ‘<table><thead><th>Mail ID</th><th>Subscription ID</th><th>Subscription Date</th></thead><tbody>’;
    $.each(data, function (key, val) {
    debugger;
    html += ‘<tr><td>’
    + ‘<a ‘ + ‘href="mailto:’ + val.MailID + ‘">’ + val.MailID + ‘</a>’ +
    ‘</td><td>’ + val.SubscriberID + ‘</td><td>’ + val.SubscribedDate + ‘</td></tr>’;
    });
    html += ‘</tbody></table>’;
    $(‘#myGrid’).html(html);
    } catch (e) {
    console.log(‘Error while formatting the data : ‘ + e.message)
    }
    },
    error: function (xhrequest, error, thrownError) {
    console.log(‘Error while ajax call: ‘ + error)
    }

    }
    );
    });
    </script>

    }
    [/js]

    Once we get the data in the success part of the ajax call we are formulating the data in an HTML table and bind the formatted html to the element myGrid.

    [html]
    <div id="myGrid"></div>
    [/html]

    Please be noted that url you give must be correct, or else you will end up with some errors. Your actions won’t work

    So we are calling our web api as http://localhost:3064/api/Subscribers. Do you remember we have already created a controller? Now we are going back to that. So we need to create an action which returns the total subscribed list from the database, so for that we will write few lines of codes as follows.

    [csharp]
    public List<tbl_Subscribers> getSubscribers()
    {
    try
    {
    using (var db = new sibeeshpassionEntities())
    {
    Subscriber sb = new Subscriber();
    return (sb.getSubcribers(db).ToList());
    }

    }
    catch (Exception)
    {

    throw;
    }
    }
    [/csharp]

    Here Subscriber is our model class, to get the reference of your model class in controller, you need to include the model namespace. We are getting a list of data in tbl_Subcribers type. Now we will concentrate on model class.

    You can see the model action codes here.

    [csharp]
    public List<tbl_Subscribers> getSubcribers(sibeeshpassionEntities sb)
    {
    try
    {
    if (sb != null)
    {
    return sb.tbl_Subscribers.ToList();
    }
    return null;
    }
    catch (Exception)
    {
    throw;
    }
    }
    [/csharp]

    This will return the data which is available in the table tbl_Subcribers in sibeeshpassion DB. It seems everything is set. Now what else we need to do? Yes we need to create some entries in the table. Please see the insertion query here.

    [sql]
    INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (1, N’sibikv4u@gmail.com’, N’2015-10-30 00:00:00′)
    INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (2, N’sibeesh.venu@gmail.com’, N’2015-10-29 00:00:00′)
    INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (3, N’ajaybhasy@gmail.com’, N’2015-10-28 00:00:00′)
    [/sql]

    So the data is inserted. Isn’t it?

    Load Data From Database Using Web API

    Load Data From Database Using Web API

    Do you know?
    Like we have RouteConfig.cs in MVC, we have another class file called WebApiConfig.cs in Web API which actually sets the routes.

    [csharp]
    routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    [/csharp]

    So shall we run our project and see the output? Before going to run, I suggest you to style the HTML table by applying some CSSs as follows.

    [css]
    <style>
    table,tr,td,th {
    border:1px solid #ccc;
    border-radius:5px;
    padding:10px;
    margin:10px;
    }

    </style>
    [/css]

    If everything goes fine, you will get the output as follows.

    Load Data From Database Using Web API

    Load Data From Database Using Web API

    That is all. We did it. Have a happy coding.

    Conclusion

    Did I miss anything that you may think which is needed? Did you try Web API yet? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

    Your turn. What do you think?

    A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

    Kindest Regards
    Sibeesh Venu

    TagsCRUD in MVCLoad Data From Database Using Web APIMVCMVC4MVC5Visual StudioVisual Studio 2013Web API
    Previous Article

    The OnePlus X has officially arrived

    Next Article

    Caching In MVC

    0
    Shares
    • 0
    • +
    • 0
    • 0
    • 0

    SibeeshVenu

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

    Related articles More from author

    • Ignite_UI_Chart_Control
      Ignite UI

      Working With IgniteUI Chart igDataChart Control

      July 14, 2016
      By SibeeshVenu
    • Chart Widgets With Server Side Data In MVC Using Angular JS And Web API Output
      .NETAngularASP.NETWeb API

      Chart Widgets With Server Side Data In MVC Using Angular JS And Web API

      March 17, 2016
      By SibeeshVenu
    • Web API With Angular JS Solution Explorer
      .NETAngularWeb API

      Web API With Angular JS

      February 11, 2016
      By SibeeshVenu
    • Media Service Created
      .NETAzureVisual Studio

      Working With Azure Media Service Account

      May 25, 2016
      By SibeeshVenu
    • .NETMVC

      Create And Consume A User Control In MVC

      July 14, 2015
      By SibeeshVenu
    • .NETVideosVisual StudioVisual Studio 2017

      What is there for a JavaScript developer in VS2017

      April 2, 2017
      By SibeeshVenu
    0

    My book

    Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

    YouTube

    MICROSOFT MVP (2016-2022)

    profile for Sibeesh Venu - Microsoft MVP

    Recent Posts

    • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
    • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
    • Easily move data from one COSMOS DB to another
    • .NET 8 New and Efficient Way to Check IP is in Given IP Range
    • Async Client IP safelist for Dot NET
    • Post Messages to Microsoft Teams Using Python
    • Get Azure Blob Storage Blob Metadata Using PowerShell
    • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
    • Integrate Azure App Insights in 1 Minute to .Net6 Application
    • Azure DevOps Service Connection with Multiple Azure Resource Group

    Tags

    Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
    • .NET
    • Achievements
    • ADO.NET
    • Android
    • Angular
    • Arduino
    • Article Of The Day
    • ASP.NET
    • Asp.Net Core
    • Automobile
    • Awards
    • Azure
    • Azure CDN
    • azure devops
    • Blockchain
    • Blog
    • Browser
    • C-Sharp Corner
    • C#
    • Career Advice
    • Code Snippets
    • CodeProject
    • Cognitive Services
    • Cosmos DB
    • CSS
    • CSS3
    • Data Factory
    • Database
    • Docker
    • Drawings
    • Drill Down Chart
    • English
    • Excel Programming
    • Exporting
    • Facebook
    • Fun
    • Gadgets
    • GitHub
    • GoPro
    • High Map
    • HighChart
    • How to
    • HTML
    • HTML5
    • Ignite UI
    • IIS
    • Interview
    • IoT
    • JavaScript
    • JQuery
    • jQuery UI
    • JQWidgets
    • JQX Grid
    • Json
    • Knockout JS
    • Linux
    • Machine Learning
    • Malayalam
    • Malayalam Poems
    • MDX Query
    • Microsoft
    • Microsoft ADOMD
    • Microsoft MVP
    • Microsoft Office
    • Microsoft Technologies
    • Microsoft Windows
    • Microsoft Windows Server
    • Mobile
    • MongoDB
    • Monthly Winners
    • MVC
    • MVC Grid
    • MySQL
    • News
    • Node JS
    • npm
    • Number Conversions
    • October 2015
    • Office 365
    • Office Development
    • One Plus
    • Outlook
    • Page
    • PHP
    • Poems
    • PowerShell
    • Products
    • Q&A
    • Raspberry PI
    • React
    • SEO
    • SharePoint
    • Skype
    • Social Media
    • Software
    • Spire.Doc
    • Spire.PDF
    • Spire.XLS
    • SQL
    • SQL Server
    • SSAS
    • SSMS
    • Storage In HTML5
    • Stories
    • Third Party Software Apps
    • Tips
    • Tools
    • Translator Text
    • Uncategorized
    • Unit Testing
    • UWP
    • VB.Net
    • Videos
    • Virtual Machine
    • Visual Studio
    • Visual Studio 2017
    • Wamp Server
    • Web API
    • Web Platform Installer
    • Webinars
    • WebMatrix
    • Windows 10
    • Windows 7
    • Windows 8.1
    • Wordpress
    • Writing

    ABOUT ME

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

    Contact Me

    • info@sibeeshpassion.com

    Pages

    • About
    • Search
    • Privacy Policy
    • About
    • Search
    • Privacy Policy
    © Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
    Go to mobile version