список стран мира с городами - PullRequest
1 голос
/ 15 апреля 2010

Есть ли какое-либо решение, чтобы показать пользователю все страны, и после выбора страны он повторно выбирает все города своей страны? быть лучшим с выбором сценария

p.s. русское название страны

Ответы [ 3 ]

1 голос
/ 15 апреля 2010

Конечно, есть решение. Вы можете иметь модели Country и City со свойствами Id и Name:

public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
}

И действие, которое даст вам все города страны:

public class CountriesController : Controller
{
    public ActionResult Index()
    {
        IEnumerable<Country> countries = Repository.GetCountries();
        return View(countries);
    }
}

public class CitiesController: Controller
{
    public ActionResult Index(string countryId)
    {
        IEnumerable<City> cities = Repository.GetCities(countryId);
        return Json(cities);
    }
}

И есть представление, похожее на это:

<%= Html.DropDownList("selectedCountry", new SelectList(Model, "Id", "Name")) %>
<%= Html.DropDownList("selectedCity", Enumerable.Empty<City>()) %>

Затем настройте JavaScript:

$(function() {
    $('#selectedCountry').change(function() {
        var selectedCountry = $(this).val();
        $.getJSON('/cities/index', { countryId: selectedCountry }, function(cities) {
            var citiesSelect = $('#selectedCity');
            citiesSelect.empty();
            $(json).each(function(i, city) {
                citiesSelect.append('<option value="' + city.Id + '">' + city.Name + '</option>');
            });
        });
    });
});
1 голос
/ 04 февраля 2011

Я думаю, лучшее решение - использовать JSON для существующей базы данных. Например, вы можете использовать geonames.org

http://jqueryui.com/demos/autocomplete/#remote-jsonp

Пример:

<meta charset="utf-8">  
    <style>
    .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
    #city { width: 25em; }
    </style>
    <script>
    $(function() {
        function log( message ) {
            $( "<div/>" ).text( message ).prependTo( "#log" );
            $( "#log" ).attr( "scrollTop", 0 );
        }

        $( "#city" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "http://ws.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.geonames, function( item ) {
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name
                            }
                        }));
                    }
                });
            },
            minLength: 2,
            select: function( event, ui ) {
                log( ui.item ?
                    "Selected: " + ui.item.label :
                    "Nothing selected, input was " + this.value);
            },
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
        });
    });
    </script>



<div class="demo">

<div class="ui-widget">
    <label for="city">Your city: </label>
    <input id="city" />
    Powered by <a href="http://geonames.org">geonames.org</a>
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

</div><!-- End demo -->



<div class="demo-description">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are cities, displayed when at least two characters are entered into the field.</p>
<p>In this case, the datasource is the <a href="http://geonames.org">geonames.org webservice</a>. While only the city name itself ends up in the input after selecting an element, more info is displayed in the suggestions to help find the right entry. That data is also available in callbacks, as illustrated by the Result area below the input.</p>
</div><!-- End demo-description -->
0 голосов
/ 15 апреля 2010

Если вам просто нужен одноразовый список (а не что-то, что постоянно обновляется), то ручная очистка страницы Russian Wikipedia для списка стран не так уж плоха. Можно было бы сделать что-то подобное со списком городов, но попытка получить полный список городов - это несколько безрассудно. Я бы попытался ограничить его до 200 лучших в мире или около того.

Примечание: я просто предполагаю, что это страница со списком стран, потому что я не говорю по-русски, но это первый результат, который я получил, когда искал его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...