Answer the question
In order to leave comments, you need to log in
How to bind 2 json when selecting country and region?
I have 2 files in json format: countries.json and region.json
In countries.json like this:
[
{
"country_id": 83,
"title_ru": "Ирак",
},
{
"country_id": 7,
"title_ru": "Грузия",
},
{
"country_id": 126,
"title_ru": "Мексика",
},
{
"country_id": 35,
"title_ru": "Белиз",
},
{
"country_id": 29,
"title_ru": "Аруба",
},
{
"country_id": 47,
"title_ru": "Бутан",
},
]
[
{
"region_id": 3977860,
"country_id": 19,
"title_ru": "Northern Territory",
},
{
"region_id": 4002131,
"country_id": 19,
"title_ru": "State of New South Wales",
},
{
"region_id": 4293504,
"country_id": 20,
"title_ru": "Bundesland Oberösterreich",
},
{
"region_id": 4290422,
"country_id": 20,
"title_ru": "Bundesland Steiermark",
},
]
<select name="country">
<option value="country-1">Российская Федерация</option>
<option value="country-2">Франция</option>
<option value="country-3">Англия</option>
</select>
<select name="area">
<option value="area-1">Московская область</option>
<option value="area-2">Ростовская область</option>
<option value="area-3">Краснодарский край</option>
</select>
Answer the question
In order to leave comments, you need to log in
Make like. This is not PHP, but the principles are similar
using System.Linq;
using HeIsBadMvc.Code;
using HeIsBadMvc.Models;
using Microsoft.AspNetCore.Mvc;
namespace HeIsBadMvc.Controllers
{
/// <summary>
/// Адресный контроллер. Занимается всеми вопросами связанными с адресами, регионами и прочим.
/// </summary>
[Route("api/address")]
[ApiController]
public class AddressController : Controller
{
private static readonly Country[] _countryes = new Country[]
{
new Country{Id = 643,
Alpha2 = "RU",
Alpha3 = "RUS",
Name = "Russia"},
};
private readonly Region[] _regions = RegionsSinglton.Instance.Items;
private readonly City[] _cityes = CityesSinglton.Instance.Items;
/// <summary>
/// Список стран в системе.
/// </summary>
/// <returns></returns>
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 86000)]
public IActionResult Get()
{
return Ok(_countryes);
}
/// <summary>
///
/// </summary>
/// <param name="country"></param>
/// <returns></returns>
[HttpGet("{country}")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 86000)]
public ActionResult<Country> Get(string country)
{
var res = _countryes.FirstOrDefault(x => x.Alpha2 == country.ToUpper());
if (res == null)
return NotFound(new { error = "Not found country" });
return res;
}
/// <summary>
/// Список регионов для страны.
/// </summary>
/// <param name="country"></param>
/// <returns></returns>
[HttpGet("{country}/regions")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 86000)]
public ActionResult GetRegions(string country)
{
var res = _countryes.FirstOrDefault(x => x.Alpha2 == country.ToUpper());
if (res == null)
return NotFound(new { error = "Not found country" });
if (res.Alpha2 == "RU")
return Ok(_regions);
return NoContent();
}
/// <summary>
/// Список городов для страны. Только Россия. Первым идет спецобьект "Вся Россия", потом Москва и Санк-Петербург, дальше сортировка по коду.
/// </summary>
/// <param name="country">Код страны, ru</param>
/// <param name="query">Поисковая фраза, по умолчанию все</param>
/// <param name="limit">Лимит для запроса</param>
/// <returns></returns>
[HttpGet("{country}/cityes")]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 86000)]
public ActionResult GetCityes(string country, [FromQuery]string query = "", [FromQuery]int limit = 10)
{
var res = _countryes.FirstOrDefault(x => x.Alpha2 == country.ToUpper());
if (res == null)
return NotFound(new { error = "Not found country" });
if (res.Alpha2 == "RU")
{
return Ok(GetFilteredCityList(query, limit));
}
return NoContent();
}
/// <summary>
/// Отдает лимитированное количество городов.
/// </summary>
/// <param name="query">Если строка не пустая то применяется фильтр</param>
/// <param name="limit"></param>
/// <returns></returns>
private City[] GetFilteredCityList(string query, int limit)
{
if (string.IsNullOrEmpty(query))
return _cityes.Take(limit).ToArray();
query = query.ToLower();
return _cityes.Where(x => x.Name.ToLower().Contains(query) || x.Slug.ToLower().Contains(query))
.Take(limit)
.ToArray();
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question