私は、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--")
私が間違ってやっていますか? さらに、ユーザーの選択を元に戻すにはどうすればよいですか?
あなたはモデルにバインドするプロパティ(選択されたオプションの値)が必要です - 'int SelectedProfile'とその' @Html.DropDownListFor(m => m.SelectedProfile、Model.listItems 、 "--Select One - ") ' –
そして、あなたは単に' spvm.listItems = new SelectList(securityProfiles、 "SecurityProfileNum"、 "SecurityProfileName"); ' –