2017-01-10 14 views
-1

国のコントロールのための2つのdropdoenlistforがあります。& City.So選択した国に基づいて都市のドロップダウンリストをバインドしたいと思います。どうすればこれを達成できますか?ここDropDownListForでの呼び出しアクションMVCでの選択

が私のコードである

AirportController.cs

// GET: Airport/Create 
    public ActionResult Create() 
    { 
     List<City> lstCity = new DACity().GetListAll(); 
     ViewBag.City = lstCity; 

     List<Country> lstCountry = new DACountry().GetListAll(); 
     ViewBag.Country = lstCountry; 

     return View(); 
    } 

Create.cshtml

<div class="form-group"> 
     @Html.LabelFor(model => model.CountryID, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownListFor(model => model.CountryID, new SelectList(ViewBag.Country, "CountryID", "CountryName"), "--select--", new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.CountryID, "", new { @class = "text-danger" }) 
     </div> 
    </div> 


    <div class="form-group"> 
     @Html.LabelFor(model => model.CityID, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownListFor(model => model.CityID, new SelectList(ViewBag.City, "CityID", "CityName"), "--select--", new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.CityID, "", new { @class = "text-danger" }) 
     </div> 
    </div> 
+1

使用を 'データを引き出すために「ajax」を使用します。 –

+0

市のデータを取得するにはjqueryを使用してください。このリンクを参考にしてください。http://www.advancesharp.com/blog/1145/mvc-dropdownlistfor-fill-on-selection-change-of-another-dropdown –

+0

[このDotNetFiddle](https://dotnetfiddle.net/1bPZym)のカスケーディングドロップダウンリストを実装する –

答えて

0

は、あなたが国のドロップダウンにクライアント側の変更イベントを追加することを検討していますか?選択に基づいて、セカンダリコントローラメソッドへのAJAX呼び出しを作成し、ドロップダウンリストに入力する都市リストを返します。

エラーが発生した場合は、ビューを返す前に都市情報をロードし、サーバー側の検証が失敗した場合にモデルの状態が保持されるようにPOSTを検討することもできます。

0

dropdownlistforのOnchangeイベントをキャッチし、dropdownlistforの選択された値をハンドラ関数に渡します。関数の内部

@Html.DropDownListFor(model => model.CountryID, new SelectList(ViewBag.Country, "CountryID", "CountryName"), "--select--", new { htmlAttributes = new { @class = "form-control", onchange = "ChangeCityValues(this.value)" } })

街のモデルのデータソースを変更し、それにYourControllerNameコントローラーで

$.ajax({ 
    type: "POST", 
    url: '@Url.Action("ChangeCitySource", "YourControllerName")', 
    data: JSON.stringify({ countryId: CountryIdValueReceivedfromDropdown }), 
    dataType: "json", 
    success: function (msg) { 
     if (true) { 
      Update city dropdown 
     } 
     else { 
      No action 
     } 
    }, 
    error: function() { 
     return "error"; 
    } 
}); 

値を渡すためにコントローラにAjaxのポストを行います

public JsonResult ChangeCitySource(string countryId) 
{ 
    // Update city source here and return some result to ajax post 
} 
関連する問題