Cascading Country, DDL in asp.net core mvc app consuming asp.net core web api (w/o make service in api n web, thur hardcode url to get data on web) using code 1st approach
Step 1. Create asp.net core web api project.
Step 2. Install nuget package.
EntityFrameworkCore
EntityFrameworkCore.SqlServer
EntityFrameworkCore.Tools
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Step 3. Apply Connection string in appsettings.json
,
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-9M9EDAA\\SQLEXPRESS; Database=DbAbpDec; Trusted_Connection= True; MultipleActiveResultSets=True; TrustServerCertificate=True;",
"providerName": "System.Data.SqlClient"
Step 4. Create Models in Models folder
i)Country.cs
using System;
using System.Collections.Generic;
namespace CityApi.Models;
public partial class Country
{
public int CountryId { get; set; }
public string Name { get; set; } = null!;
public virtual ICollection<State> States { get; set; } = new List<State>();
}
ii) State.cs
using System;
using System.Collections.Generic;
namespace CityApi.Models;
public partial class State
{
public int StateId { get; set; }
public string Name { get; set; } = null!;
public int CountryId { get; set; }
public virtual ICollection<City> Cities { get; set; } = new List<City>();
public virtual Country Country { get; set; } = null!;
}
iii) City.cs
using System;
using System.Collections.Generic;
namespace CityApi.Models;
public partial class City
{
public int CityId { get; set; }
public string Name { get; set; } = null!;
public int StateId { get; set; }
public virtual State State { get; set; } = null!;
}
Step 5. Make Data folder and Create DbAbpDecContext file
DbAbpDecContext .cs
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace CityApi.Models;
public partial class DbAbpDecContext : DbContext
{
public DbAbpDecContext()
{
}
public DbAbpDecContext(DbContextOptions<DbAbpDecContext> options)
: base(options)
{
}
public virtual DbSet<City> Cities { get; set; }
public virtual DbSet<Country> Countries { get; set; }
public virtual DbSet<State> States { get; set; }
Step 6. AddDbContext service in Program.cs
builder.Services.AddDbContext<DbAbpDecContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Step 7. Create LocationController
using CityApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace CityApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LocationController : ControllerBase
{
private readonly DbAbpDecContext _db;
public LocationController(DbAbpDecContext db)
{
_db = db;
}
// Get all Cities (GET)
[HttpGet]
public async Task<IActionResult> GetCities()
{
try
{
// Cities ko asynchronously fetch karte hain
var cities = await _db.Cities.ToListAsync();
// Agar Cities list null ya empty ho
if (cities == null || !cities.Any())
{
return NotFound("No cities found.");
}
// Agar cities milti hain, to OK response bhejte hain
return Ok(cities);
}
catch (Exception ex)
{
// Agar koi exception aata hai to 500 Internal Server Error bhejte hain
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// Get all States (GET)
[HttpGet]
public async Task<IActionResult> GetStates()
{
try
{
// States ko asynchronously fetch karte hain
var states = await _db.States.ToListAsync();
// Agar States list null ya empty ho
if (states == null || !states.Any())
{
return NotFound("No states found.");
}
// Agar states milti hain, to OK response bhejte hain
return Ok(states );
}
catch (Exception ex)
{
// Agar koi exception aata hai to 500 Internal Server Error bhejte hain
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// Get all Countries (GET)
[HttpGet]
public async Task<IActionResult> GetCountries()
{
try
{
// Countries ko asynchronously fetch karte hain
var countries = await _db.Countries.ToListAsync();
// Agar countries list null ya empty ho
if (countries == null || !countries.Any())
{
return NotFound("No countries found.");
}
// Agar countries milti hain, to OK response bhejte hain
return Ok(countries);
}
catch (Exception ex)
{
// Agar koi exception aata hai to 500 Internal Server Error bhejte hain
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
}
=====================================================
Consume api in .net core mvc app.
Step 8. Create .net core mvc app.
Step 9. Install nuget package
Newtonsoft.Json
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
Step 10. Apply Api BaseUrl in appsettings.json
,
"ApiSettings": {
"BaseUrl": "https://localhost:7287/"
}
Step 11. Create Model (Copy paste models from api models)
Step 12. Create LocationController
using CityWebApp.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace CityWebApp.Controllers
{
public class LocationController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public LocationController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<IActionResult> Index()
{
var client = _httpClientFactory.CreateClient();
var countries = await client.GetFromJsonAsync<List<Country>>("https://localhost:7196/api/country");
ViewBag.Countries = new SelectList(countries, "CountryId", "Name");
return View();
}
[HttpGet]
public async Task<JsonResult> GetStates(int countryId)
{
var client = _httpClientFactory.CreateClient();
var states = await client.GetFromJsonAsync<List<State>>("https://localhost:7196/api/state");
var statesList = states.Where(s => s.CountryId == countryId).ToList();
return Json(statesList);
}
[HttpGet]
public async Task<JsonResult> GetCities(int stateId)
{
var client = _httpClientFactory.CreateClient();
var cities = await client.GetFromJsonAsync<List<City>>("https://localhost:7196/api/city");
var citiesList = cities.Where(c => c.StateId == stateId).ToList();
return Json(citiesList);
}
}
}
No comments: