better way to load 2 dropdown in mvc

后端 未结 5 501
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 03:05

This is how i am loading on page load state and city dropdown:

My Controller method:

This is the first method which is calling when page is

5条回答
  •  不思量自难忘°
    2020-11-22 03:29

    How about using Knockout?

    Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model

    You have to use ajax for your cities. But with knockout you dont need to write

    var html = ''; $(responce).each(function () { html += ''}); $("#ddlCity").html(html);

    in your javascript.Knockout makes it simple.

    You can simply write:

            function CityModel() {
            var self = this; // that means this CityModel
            self.cities = ko.observableArray([]);
            self.getCities = function () {
                $.ajax({
                    url: "/Home/GetCities",
                    data: { id: $(obj).val() },
                    contentType: "application/json",
                    success: self.cities
                });
            }
        }
        ko.applyBindings(new CityModel());
    

    thats all. But you have to bind your data into html elements. Instead of using : @Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id="ddlCity"})

    You can use:

        
    

    or you can mix razor and knockout:

    @Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id="ddlCity",data_bind:"options:cities,optionsValue:\"Id\",optionsText:\"CityName\""})
    

    One more thing you have to call GetCities when State changes, you can :

    @Html.DropDownList("State", States, "Select State", new {data_bind:"event:\"change\":\"$root.GetCities\""})
    

    Dont be scare with \"\" things this because " is an escape character and we have to say to razor i want to use " by using \ before it.

    You can find more info about knockout :Knockout

    And mixing with razor: Razor and Knockout

    Ps: yes using knockout is suspend us from Razor and Mvc. You have to write another ViewModel . But like this situations ko is helpful. Mixing razor and knockout is another option for you.

提交回复
热议问题