Hello guys, I’m back with my ASP.NET Web API series. In one of my previous articles, one guy asked me how can we use Web API with Web Forms in Visual Studio. Let’s a look at ASP.NET Web API series,
It’s pretty simple. Go ahead, open Visual Studio 2013, go to New and choose the Project.
Expand Installed > Templates > Visual C# and choose ASP.NET Web Application from the menu, give a reasonable name to your Web API project, which you want to do and finally click “OK” button.
From the given templates, select empty template and add a core reference of the Web Forms.
Here, my project is ready for use. In Solution Explorer, you can see the models folder and code at the backend Global.asax file, which is responsible for containing the URL route.
I want to call Web API with JavaScript and jQuery. Hence, add the form NuGet Package Manager for the current project. Right click on the project and select NuGet.
With the help of the following screenshot, you can install jQuery to your project:
Now add a model class, right click Models folder and add a class to it.
Select a class and give a reasonable name to your model class.
In the model class, I’ve created five properties of the student details.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace WebAPIWithWebForm.Models
- {
- public class Student
- {
- public int StudRollNO { get; set; }
- public string StudName { get; set; }
- public string StudAddress { get; set; }
- public int StudMONO { get; set; }
- public string StudCourse { get; set; }
-
- }
- }
Now, I need to add a Web API Controller class to my project. It will handle HTTP requests for the Web API. Right click on the project and add a New Item.
Select Web API Controller class from the list and give it a proper name.
Thus, my College Controller that is Web API Controller drives from API Controller. The data of Student is stored in a fixed array inside the controller class. Click to resolve it from the Model class.
The GetAllStudents method returns the entire list of the students as an IEnumerable<Student> type.
The GetStudent method returns a single student record by its ID. If there is no record of matching ID, it will return the null value.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using WebAPIWithWebForm.Models;
-
- namespace WebAPIWithWebForm
- {
- public class CollegeController : ApiController
- {
- Student[] stud = new Student[]
- {
- new Student{StudRollNO=1, StudName="Amit",
- StudAddress="Noida", StudMONO=123, StudCourse="MCA"},
- new Student{StudRollNO=2, StudName="Rahgvendra",
- StudAddress="Hardoi", StudMONO=321, StudCourse="BCA"},
- new Student{StudRollNO=3, StudName="Ankur",
- StudAddress="Lucknow", StudMONO=567, StudCourse="MBA"}
- };
- public IEnumerable<Student> GetallStudents()
- {
- return stud;
- }
- public IHttpActionResult GetStudent(int id)
- {
- var record = stud.FirstOrDefault(x => x.StudRollNO==id);
- if (record == null)
- {
- return NotFound();
- }
- return Ok(record);
- }
- }
- }
Thus, if you call Web API with jQuery, you need to add a Web Form, give a name to it and hit the Add button.
Initially, add a reference to the jQuery source file in the head section. I’m using here some script of JavaScript and jQuery. jQuery getJSON function sends an AJAX request. Make a loop for the list of the students and add a table row for the students. Finally, append the row.
Create a table in the Web form as well. Similar to the property in the Model class, enter the Student details.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Students.aspx.cs" Inherits="WebAPIWithWebForm.Test" %>
-
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <title></title>
-
- <script src="Scripts/jquery-3.0.0.min.js"></script>
-
- <script type="text/javascript">
- function getStudents() {
- $.getJSON("api/College",
- function(data) {
- $('#stud').empty();
-
-
- $.each(data, function(key, val) {
-
- var row = '<tr><td>' + val.StudName +
- '</td><td>' + val.StudAddress + '</td><td>' +
- val.StudMONO + '</td><td>' + val.StudCourse +
- '</td></tr>';
- $("#stud").append(row);
-
- });
- });
- }
- $(document).ready(getStudents);
- </script>
-
- </head>
-
- <body>
- <form id="form1" runat="server">
- <h2> Here is the Students Record</h2>
- <table>
- <thead>
- <tr>
- <th>StudName</th>
- <th>StudAddress</th>
- <th>StudMONO</th>
- <th>StudCourse</th>
- </tr>
- </thead>
- <tbody id="stud">
- </tbody>
- </table>
- </form>
- </body>
-
- </html>
For Web API with Web Forms, this is the main step to add routing information, that routed to the controller directly. For it, add a namespace.
- using WebAPIWithWebForm.Models;
Add some implementation, as shown below:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Routing;
- using System.Web.Security;
- using System.Web.SessionState;
- using System.Web.Http;
-
- namespace WebAPIWithWebForm {
- public class Global: System.Web.HttpApplication {
- protected void Application_Start(object sender, EventArgs e) {
- RouteTable.Routes.MapHttpRoute(
- name: "MyAPI",
- routeTemplate: "api/{controller}/{id}",
- defaults: new {
- id = System.Web.Http.RouteParameter.Optional
- }
- );
- }
- }
- }
Save your project and call the respective Controller along with API. Hence, you can see, we got our Controller’s GetAllStudents method.
Now, call Web Form page, where you’ll get your expected output.
Thanks for reading this article. Stay tuned with us for more on ASP.NET Web API.