Simple Cascading Country, State, City DDL in asp.net core mvc app consuming asp.net core web api using db1st approach
Simple Cascading Country, State, City DDL in asp.net core mvc app consuming asp.net core web api using db1st approach
Step 1. Create asp.net core web api project.
Step 2. Install nuget package.
EntityFrameworkCore
EntityFrameworkCore.SqlServer
EntityFrameworkCore.Tools
EntityFrameworkCore.Design
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" 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. Thru db 1st approach scaffold in PCM
Scaffold-dbContext
"Server=DESKTOP-9M9EDAA\\SQLEXPRESS; Database=DbAbpDec; Trusted_Connection= True; MultipleActiveResultSets=True; TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer -OutpuDir Models
After getting the auto-generated DbContext file delete the warning message(connection string) .
Step 4: Add connection string in appsetting.json file
,
"ConnectionStrings": {
"DefaultConnection": "Server = DESKTOP-9M9EDAA\\SQLEXPRESS; Database = DbAbpDec; Trusted_Connection = True; MultipleActiveResultSets = True; TrustServerCertificate = True;"
}
Step 5: Add service in program.cs file
builder.Services.AddDbContext<DbAbpDecContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Step 6: Add Country, State, City in Cotroller folder
[Route("api/[controller]")]
[ApiController]
public class CountryController : ControllerBase
{
private readonly DbAbpDecContext _db;
public CountryController(DbAbpDecContext db)
{
_db = db;
}
// 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}");
}
}
}
StateController.cs
StateController.cs
[Route("api/[controller]")]
[ApiController]
public class StateController : ControllerBase
{
private readonly DbAbpDecContext _db;
public StateController(DbAbpDecContext db)
{
_db = db;
}
// Get all States (GET)
[HttpGet]
public async Task<IActionResult> GetStates()
{
try
{
// States ko asynchronously fetch karte hain
var states = await _db.States.ToListAsync();
// Agar Countries list null ya empty ho
if (states == null || !states.Any())
{
return NotFound("No state found.");
}
// Agar countries 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}");
}
}
}
CityController.cs
[Route("api/[controller]")]
[ApiController]
public class CityController : ControllerBase
{
private readonly DbAbpDecContext _db;
public CityController(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}");
}
}
}
=========================================================================
=========================================================================
Step1. API ko direct call kiye h bina service banaye
consume API in web app
,
"ApiSettings": {
"BaseUrl": "https://localhost:7287/"
}
Step 2. copy paste models from API
Step3 .LocationController.cs
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);
}
}
Step 4 Index.cshtml
<div class="form-group">
<label>Country</label>
@Html.DropDownList("CountryId", ViewBag.Countries as SelectList, "Select Country", new { @class = "form-control" })
</div>
<div class="form-group">
<label>State</label>
@Html.DropDownList("StateId", new SelectList(new List<string>()), "Select State", new { @class = "form-control" })
</div>
<div class="form-group">
<label>City</label>
@Html.DropDownList("CityId", new SelectList(new List<string>()), "Select City", new { @class = "form-control" })
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
var countryId = $(this).val();
$("#StateId").empty();
$("#CityId").empty();
$("#StateId").append('<option value="">Select State</option>');
$("#CityId").append('<option value="">Select City</option>');
if (countryId) {
$.get("/Location/GetStates", { countryId: countryId }, function (data) {
$.each(data, function (i, state) {
$("#StateId").append('<option value="' + state.stateId + '">' + state.name + '</option>');
});
});
}
});
$("#StateId").change(function () {
var stateId = $(this).val();
$("#CityId").empty();
$("#CityId").append('<option value="">Select City</option>');
if (stateId) {
$.get("/Location/GetCities", { stateId: stateId }, function (data) {
$.each(data, function (i, city) {
$("#CityId").append('<option value="' + city.cityId + '">' + city.name + '</option>');
});
});
}
});
});
</script>
Simple Cascading Country, State, City DDL in asp.net core mvc app consuming asp.net core web api using db1st approach
Reviewed by Rikesh
on
December 30, 2024
Rating:
No comments: