0

別のドロップダウンリストを追加したい。以下のコードは 1 つのドロップダウンで機能しますが、カテゴリに追加するにはどうすればよいですか?

public  ActionResult Create()
        {
            var ddl = new Users();
            ddl.DropDowns = userRepository.Getddl("Departments").Select(c => new SelectListItem
                                                                    {
                                                                        Value = c.DropdownID.ToString(),
                                                                        Text = c.DropdownText
                                                                    });


            ViewData["ListofProfiles"] = new SelectList(ListofProfiles, "Value", "Text");

            return View(ddl);
        }
4

1 に答える 1

1

ViewDataアプローチを避けるようにしてください。これを行うには、厳密に型指定された方法に切り替えます。View Model に別のプロパティを追加して、もう 1 つのドロップダウン項目を保持します

public class User
{
  public int SelectedCountry { set;get;}
  public int SelectedProfile { set;get;}
  public List<SelectListItem> Countries  {set;get;}
  public List<SelectListItem> Profiles {set;get;}

  public User()
  {
     Countries =new List<SelectListItem>(); 
     Profiles =new List<SelectListItem>(); 
  }
}

GETアクションにコレクションを設定します

public ActionResult Create()
{
  var vm=new User();
  vm.Countries=GetCountryItems();
  vm.Profiles=GetProfileItems();  
  return View(vm);
}

WhereGetCountryItemsGetProfileItemsは、db から国とプロファイルの SelectListItem オブジェクトのリストを返す 2 つのメソッドです。

コントローラを FAT にしないでください。シンプルで清潔に保つだけです。リポジトリからデータを取得するコードを別のレイヤーに移動します。読みやすく、維持しやすい:)

そして、強く型付けされたビューでは、

@mode User
@using(Html.BeginForm())
{
  @Html.DropDownListFor(m => m.SelectedCountry,
                     new SelectList(Model.Countries, "Value", "Text"), "Select")
  @Html.DropDownListFor(m => m.SelectedProfile,
                     new SelectList(Model.Profiles, "Value", "Text"), "Select")
 <input type="submit" />
} 
于 2012-10-15T13:14:24.127 に答える