我需要创建一个选择列表,保留状态,这不是传递给视图的模型的一部分。我想我应该使用ViewBag将List传递给View?有关实现的建议以及如何保留选择列表的状态(如何将选定的值再次传递给操作和视图(可能的方法)?
截至目前的行动:
public ActionResult Images(string x, string y)
{
//some code
ContentPage cp = this.ContentPage;
return View(cp);
}
//Post to action with same name:
[HttpPost]
public ActionResult Images(string someParameter)
{
ContentPage cp = this.ContentPage;
return View(cp);
}
截至目前的观点:
@model ContentPage
@{
ViewBag.Title = "Images";
CmsBaseController controller = (this.ViewContext.Controller as CmsBaseController);
}
@using (Html.BeginForm())
{
<div>
//This should go to List<SelectListItem> as I understand
<select name="perpage" id="perpage" onchange='submit();'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
}
谢谢!!!
答案 0 :(得分:11)
你看过this SO question了吗?如果您想使用ViewBag / ViewData传入该列表,那么答案似乎就可以了。
那说,为什么不创建一个快速视图模型并将其存储在那里?这真的是一个简单的方法。
我不知道您的ContentPage模型是什么,但您当然可以创建一个ContentPageViewModel,其中包含页面所需的任何内容(包括选择列表的值)。
示例:强>
例如,在viewmodel上有一个属性来保存选择和一个包含可能值枚举的属性就足够了。像这样:
public class MyViewModel
{
...
public int SelectedId { get; set; }
...
public IEnumerable<Choice> Choices { get; set; }
}
其中,在我的示例中,Choice是一个具有两个属性的类,一个包含一些标识符,另一个包含要显示的文本。像这样:
public class Choice
{
public int Id { get; set; }
public string Text { get; set; }
}
然后你可能只有一个DropDownListFor
处理显示/选择工作。像这样:
@model MyViewModel
@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.Choices, "Id", "Text"), "Choose... ")
返回控制器的操作,视图模型的SelectedId
将填充相应的选择ID,用于选择选择的视图下拉列表。