Pass (Send) multiple parameters to ASP.Net Web API Controller using VB.Net

makumbi
 
on Mar 11, 2021 03:27 AM
1759 Views

I have managed to generate this api automatically using scafold API2 read write with entity framework.

But by default this code returns records by id yet, i wanted to return records by gender or even use two parameters gender and amount.

How can i modify this code below to make that happen? 

' GET: api/Employees/5

<ResponseType(GetType(Employee))>
Function GetEmployee(ByVal id As Integer) As IHttpActionResult
    Dim employee As Employee = db.Employees.Find(id)
    If IsNothing(employee) Then
        Return NotFound()
    End If
    Return Ok(employee)
End Function

But my changes is modifying this code to make it able to get list from the list by gender as a parameter

Or even using to parameters like filter out employee list using gender and a specific amount

Imports System.Data
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Imports System.Linq
Imports System.Net
Imports System.Net.Http
Imports System.Web.Http
Imports System.Web.Http.Description
Imports NEWEMPAPI

Namespace Controllers
    Public Class EmployeesController
        Inherits System.Web.Http.ApiController

        Private db As New EmployeeDBContext

        ' GET: api/Employees
        Function GetEmployees() As IQueryable(Of Employee)
            Return db.Employees
        End Function

        ' GET: api/Employees/5
        <ResponseType(GetType(Employee))>
        Function GetEmployee(ByVal id As Integer) As IHttpActionResult
            Dim employee As Employee = db.Employees.Find(id)

            If IsNothing(employee) Then
                Return NotFound()
            End If


            Return Ok(employee)
        End Function

        ' PUT: api/Employees/5
        <ResponseType(GetType(Void))>
        Function PutEmployee(ByVal id As Integer, ByVal employee As Employee) As IHttpActionResult
            If Not ModelState.IsValid Then
                Return BadRequest(ModelState)
            End If

            If Not id = employee.ID Then
                Return BadRequest()
            End If

            db.Entry(employee).State = EntityState.Modified

            Try
                db.SaveChanges()
            Catch ex As DbUpdateConcurrencyException
                If Not (EmployeeExists(id)) Then
                    Return NotFound()
                Else
                    Throw
                End If
            End Try

            Return StatusCode(HttpStatusCode.NoContent)
        End Function

        ' POST: api/Employees
        <ResponseType(GetType(Employee))>
        Function PostEmployee(ByVal employee As Employee) As IHttpActionResult
            If Not ModelState.IsValid Then
                Return BadRequest(ModelState)
            End If

            db.Employees.Add(employee)
            db.SaveChanges()

            Return CreatedAtRoute("DefaultApi", New With {.id = employee.ID}, employee)
        End Function

        ' DELETE: api/Employees/5
        <ResponseType(GetType(Employee))>
        Function DeleteEmployee(ByVal id As Integer) As IHttpActionResult
            Dim employee As Employee = db.Employees.Find(id)
            If IsNothing(employee) Then
                Return NotFound()
            End If

            db.Employees.Remove(employee)
            db.SaveChanges()

            Return Ok(employee)
        End Function

        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If (disposing) Then
                db.Dispose()
            End If
            MyBase.Dispose(disposing)
        End Sub

        Private Function EmployeeExists(ByVal id As Integer) As Boolean
            Return db.Employees.Count(Function(e) e.ID = id) > 0
        End Function
    End Class
End Namespace

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 11, 2021 06:39 AM
on Dec 30, 2021 10:17 AM

Hi makumbi,

You can wrap multiple parameters in a single class and use that class as a parameter to your Web API controller method.

Refer below code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Namespaces

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Http

Model

Public Class CustomerModel
    Public Property Name As String
    Public Property City As String
End Class

ApiController

Public Class CustomerAPIController
    Inherits ApiController

    <Route("api/CustomerAPI/GetCustomers")>
    <HttpPost>
    Public Function GetCustomers(ByVal customer As CustomerModel) As List(Of Customer)
        Dim customers As List(Of Customer) = New List(Of Customer)()
        Dim constr As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
        Using con As SqlConnection = New SqlConnection(constr)
            Dim query As String = "SELECT CustomerID,ContactName,City FROM Customers WHERE (ContactName LIKE @Name + '%' OR @Name IS NULL) AND (City = @City OR @City IS NULL)"
            Using cmd As SqlCommand = New SqlCommand(query)
                cmd.Connection = con
                cmd.Parameters.AddWithValue("@Name", If(Not String.IsNullOrEmpty(customer.Name), customer.Name, CObj(DBNull.Value)))
                cmd.Parameters.AddWithValue("@City", If(Not String.IsNullOrEmpty(customer.City), customer.City, CObj(DBNull.Value)))
                con.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(New Customer With {
                            .CustomerID = sdr("CustomerID").ToString(),
                            .ContactName = sdr("ContactName").ToString(),
                            .City = sdr("City").ToString()
                        })
                    End While
                End Using

                con.Close()
            End Using
        End Using

        Return customers
    End Function

    Public Class Customer
        Public Property CustomerID As String
        Public Property ContactName As String
        Public Property City As String
    End Class
End Class

HTML

Name:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br />
City:<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="Search" />
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
    </Columns>
</asp:GridView>

Namespaces

Imports System.Net
Imports System.Text
Imports System.Web.Script.Serialization

Code

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            Me.PopulateGridView()
        End If
    End Sub

    Protected Sub Search(ByVal sender As Object, ByVal e As EventArgs)
        Me.PopulateGridView()
    End Sub

    Private Sub PopulateGridView()
        Dim apiUrl As String = "http://localhost:26404/api/CustomerAPI"
        Dim input As Object = New With {Key
            .Name = txtName.Text.Trim(), Key
            .City = txtCity.Text.Trim()
        }
        Dim inputJson As String = (New JavaScriptSerializer()).Serialize(input)
        Dim client As WebClient = New WebClient()
        client.Headers("Content-type") = "application/json"
        client.Encoding = Encoding.UTF8
        Dim json As String = client.UploadString(apiUrl & "/GetCustomers", inputJson)
        gvCustomers.DataSource = (New JavaScriptSerializer()).Deserialize(Of List(Of Customer))(json)
        gvCustomers.DataBind()
    End Sub

    Public Class Customer
        Public Property CustomerID As String
        Public Property ContactName As String
        Public Property City As String
    End Class

Screenshot