G
G
Genri_Rus2019-12-08 16:59:32
JavaScript
Genri_Rus, 2019-12-08 16:59:32

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": "Бутан",
 },
]

In region.json like this:
[
 {
   "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",
 },
]

How to bind 2 json at all?
Let's say there is one select with countries:
<select name="country">
         <option value="country-1">Российская Федерация</option>
         <option value="country-2">Франция</option>
         <option value="country-3">Англия</option>
</select>

And 2 select with regions
<select name="area">
         <option value="area-1">Московская область</option>
         <option value="area-2">Ростовская область</option>
         <option value="area-3">Краснодарский край</option>
</select>

How to display all its regions when selecting a specific country?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2019-12-08
@Genri_Rus

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 question

Ask a Question

731 491 924 answers to any question