2016-10-10 5 views
0

countries.idのcodes.countryidに外部キー制約を持つ2つのテーブル、コード、国があります - 私はVisual Basic内のコントローラmvc setupによって与えられた基本的なcrudを使用していますスタジオ15を使用していますが、テキスト入力をcountryidのselectに置き換えたいので、ユーザがIDをintとして入力するようにドロップダウンから国を選択することができます。ASP MVC EF6リストとして外部キーテーブルにアクセス

提供されたモデルを使用して各国のリストにアクセスするにはどうすればよいですか?以下のサンプルの剃刀コード。別のモデルから国のリストを取得する必要がありますか?

<div class="form-group"> 
      <label for="CountryId" class="control-label col-md-2">Country</label> 
      <select name="CountryId" class="form-control" required> 
       <option value="">Please select ...</option> 
/* Model.Countries is not available even after a foreignkey constraint? */ 
       @foreach(var i in Model.Countries) 
       { 
        <option value="@i.id">@i.Name</option> 
       } 
      </select> 
      @Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" }) 
      @Html.LabelFor(model => model.CountryId, htmlAttributes: new { @class = "control-label col-md-2" }) 
     </div> 

答えて

0

ViewBag変数をコントローラのアクションに国のリストとともに設定する必要があります。

あなたは、コントローラ内部のDBコンテキストを持っていると仮定すると、あなたのアクション

ViewBag.CountriesList = new SelectList(_context.countries.ToList(), "Id", "Name"); 

を次のコードを入れて、あなたのビュー内の以下のようにそれを使用する必要があります

@Html.DropDownListFor(a => a.countryId, (SelectList)ViewBag.CountriesList , htmlAttributes: new { @class = "form-control" }) 
関連する問題