ASP.NET MVC Dropdown Selected Item
我的索引页面上有一个DropDownListFor,而我的创建页面上有一个。 这两个下拉列表都具有相同的目的。
我想要的是当用户在索引页面的"索引"下拉列表中选择一个项目时,它将所选项目的值(即GUID)保存到会话中,并且在"创建"页面加载时,我希望其中的下拉列表根据 在会话中的GUID上。
当用户单击"创建"并转到创建页面时,我只是在设置一个对象并将该对象发送到"创建视图"。
编辑:
我通过执行以下操作将用户转到创建页面:
1 | Html.ActionLink("Create New Listing","Create", null, new { @class ="btn btn-primary" })) |
如何将所选项目的GUID发送到视图?
我猜你有这样的情况。 这是索引视图:
1 2 3 4 5 6 7 8 9 10 | @model Models.IndexViewModel @{ ViewBag.Title ="Index"; } Index @using (Html.BeginForm("SaveGuid","Flow")) { Html.DropDownListFor(x => x.SelectedGuid, Model.Guids, new { onchange ="this.form.submit();" }); } |
这是索引模型:
1 2 3 4 5 | public class IndexViewModel { public Guid SelectedGuid { get; set; } public SelectList Guids { get; set; } } |
Index和SaveGuid动作如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 | private List<Guid> Guids = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() }; // for testing only public ActionResult Index() { var model = new IndexViewModel { Guids = new SelectList(Guids, Guids.First()) }; return View(model); } public ActionResult SaveGuid(IndexViewModel model) { Session["SelectedGuid"] = model.SelectedGuid; return new RedirectResult("Create"); } |
创建视图看起来像这样...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @model MvcBootStrapApp.Models.CreateViewModel @{ ViewBag.Title ="Create"; } Create @using (Html.BeginForm("SaveGuid","Flow")) { @Html.DropDownListFor(x => x.SelectedGuid, Model.Guids, new { onchange ="this.form.submit();" }); } @using (Html.BeginForm("SaveCreate","Flow")) { // setup other controls <input type="submit" value="Submit" /> } |
使用这样的CreateViewModel ...
1 2 3 4 5 6 7 | public class CreateViewModel { public Guid SelectedGuid { get; set; } public SelectList Guids { get; set; } // include other model properties } |
Create和CreateSave ActionResults看起来像这样...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public ActionResult Create() { Guid selectedGuid = Guids.First(); if (Session["SelectedGuid"] != null) selectedGuid = (Guid)Session["SelectedGuid"]; return View(new CreateViewModel { Guids = new SelectList(Guids, selectedGuid), SelectedGuid = selectedGuid }); } public ActionResult SaveCreate(CreateViewModel model) { // save properties return new RedirectResult("Index"); } |
我使用两种形式来允许更改选定的Guid并回发所有Create属性。
如果要使用Session,我想您需要使用表单将其发布到ActionResult来保存下拉列表的值,然后重定向到"创建"页面。
1 2 3 4 5 | public ActionResult SaveGuid(Guid value) { Session["SelectedGuid"] = value; return new RedirectResult("Create"); } |
然后在"创建ActionResult"中,将"会话"值传递给"创建视图"的模型。
1 2 3 4 5 | public ActionResult Create() { var selectedGuid = (Guid)Session["SelectedGuid"]; return View(new CreateViewModel { SelectedGuid = selectedGuid, /* include other properties */ }; } |
在您的视图中,可以在传递给DropDownListFor ...的SelectList上设置所选选项。
1 2 3 4 | @Html.DropDownListFor( x => x.SelectedGuid, new SelectList(Model.ListOfStuff,"Key","Value", Model.SelectedGuid) ) |