Hi anjali600,
I have created a sample by passing the Model as parameter to the WebAPI.
For creating WebAPI in Core refer below article.
Create Web API in .Net Core
Refer the example.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
CustomerModel
public class CustomerModel
{
[Key]
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
}
PersonModel
public class PersonModel
{
public string Name { get; set; }
}
DBContext
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<CustomerModel> Customers { get; set; }
}
WebAPI
[Route("api/[controller]")]
[ApiController]
public class CustomerAPIController : ControllerBase
{
private DBCtx Context { get; }
public CustomerAPIController(DBCtx _context)
{
this.Context = _context;
}
[Route("GetCustomers")]
[HttpPost]
public List<CustomerModel> GetCustomers(PersonModel model)
{
return (from c in this.Context.Customers.Take(10)
where c.ContactName.StartsWith(model.Name) || string.IsNullOrEmpty(model.Name)
select c).ToList();
}
}
Namespaces
using System.Net.Http;
using Newtonsoft.Json;
using System.Text;
Controller
public class HomeController : Controller
{
// GET: Home
public IActionResult Index()
{
ViewBag.Customers = GetCustomers(new PersonModel { Name = "" });
return View();
}
[HttpPost]
public IActionResult Index(PersonModel model)
{
ViewBag.Customers = GetCustomers(model);
return View();
}
private List<CustomerModel> GetCustomers(PersonModel model)
{
List<CustomerModel> customers = new List<CustomerModel>();
string apiUrl = "https://localhost:44318/api/CustomerAPI/GetCustomers";
HttpContent body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = client.PostAsync(apiUrl, body).Result;
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync();
customers = JsonConvert.DeserializeObject<List<CustomerModel>>(content.Result);
}
return customers;
}
}
View
@using WebAPI_EF_MVC_Core.Models
@model PersonModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<span>Name:</span>
<input type="text" name="name" asp-for="Name" />
<input type="submit" value="Search" />
</form>
<hr />
@if (ViewBag.Customers != null)
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
</tr>
@foreach (CustomerModel customer in ViewBag.Customers)
{
<tr>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
</tr>
}
</table>
}
</body>
</html>
Screenshot