better way to load 2 dropdown in mvc

后端 未结 5 524
没有蜡笔的小新
没有蜡笔的小新 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:19

    Here's how I'd do it without the page refresh, assuming the list of cities isn't too long. I'm assuming you can create a GetStatesAndCities method to return a Dictionary.

    public ActionResult Index()
    {
      Dictionary> statesAndCities = GetStatesAndCities();
      ViewBag.StatesAndCities = Json(statesAndCities);
    }
    

    Then in the view:

    var states = JSON.parse(@ViewBag.StatesAndCities);
    
    function loadCities(obj) {
        var cities = states[$(obj).val()];
        var html = '';
        $(cities).each(function () {
            html += ''
        });
        $("#ddlCity").html(html);
    }
    

    This way when the state is changed the cities field with update immediately with no need for callback.

提交回复
热议问题