2017-03-30 7 views
1

私は、ViewBagではなく強く型付けされたViewModelを使用して、ドロップダウンリストにデータを表示しようとしています。私はユーザーの選択を元に戻したい。ASPMVC4 ViewModelとドロップダウンリストを使用してユーザーを選択するにはどうすればよいですか?

は私のコントローラのコードは次のようになります。

public ActionResult Index() 
{ 
ReportsHelper rh = new ReportsHelper(); 
List<SecurityProfile> securityProfiles = rh.GetSecurityProfiles(); 

List<SelectListItem> listItems = new List<SelectListItem>(); 
foreach (SecurityProfile secProf in securityProfiles) 
{ 
SelectListItem item = new SelectListItem(); 
item.Value = secProf.SecurityProfileNum.ToString(); 
item.Text = secProf.SecurityProfileName; 
listItems.Add(item); 
} 

var spvm = new SecurityProfileViewModel(); 
spvm.listItems = listItems; 
return View(spvm); 
} 

私のViewModelには、次のようになります。

public class SecurityProfileViewModel 
{ 
public IEnumerable<SelectListItem> listItems { get; set; } 
} 

マイビューは次のようになります。

@model ClearWeighWebReporting.ViewModels.SecurityProfileViewModel 

@{ 
ViewBag.Title = "Index"; 
} 

@Html.DropDownListFor(Model.listItems, "--Select One--") 

上記のコードはありません作業。私は、コントローラのコードの次の行にビルドエラーが出ます:

spvm.listItems = listItems; 

そして私は、ビューのコードの次の行にエラーが表示されます。

@Html.DropDownListFor(Model.listItems, "--Select One--") 

私が間違ってやっていますか? さらに、ユーザーの選択を元に戻すにはどうすればよいですか?

+0

あなたはモデルにバインドするプロパティ(選択されたオプションの値)が必要です - 'int SelectedProfile'とその' @Html.DropDownListFor(m => m.SelectedProfile、Model.listItems 、 "--Select One - ") ' –

+0

そして、あなたは単に' spvm.listItems = new SelectList(securityProfiles、 "SecurityProfileNum"、 "SecurityProfileName"); ' –

答えて

0

ビューモデルに新しいプロパティを追加して、選択したオプション値を保持します。

public class SecurityProfileViewModel 
{ 
    public int SelectedProfileNum { set;get;} 
    public IEnumerable<SelectListItem> listItems { get; set; } 
} 

ここでは、DropDownListForヘルパーメソッドを使用します。

@Html.DropDownListFor(x=>x.SelectedProfileNum,Model.listItems,"Select--") 

これはname ="SelectedProfileNum"

1つの提案でSELECT要素のマークアップを生成します:C#クラスを書くときPascalCasingを使用してみてくださいと一致しています。 listItemsからListItems

関連する問題