Asp.net mvc选择列表

mis*_*hap 3 asp.net-mvc selectlist selectlistitem asp.net-mvc-3

我需要创建一个选择列表,保留状态,这不是传递给视图的模型的一部分.我想我应该使用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);
 }
Run Code Online (Sandbox Code Playgroud)

截至目前的观点:

@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>
}
Run Code Online (Sandbox Code Playgroud)

谢谢!!!

its*_*att 11

你看过这个问题吗?如果您想使用ViewBag/ViewData传入该列表,那么它的答案看起来就好了.

也就是说,为什么不创建一个快速视图模型并将其存储在那里?这真的是一个简单的方法.

我不知道您的ContentPage模型是什么,但您当然可以创建一个ContentPageViewModel,其中包含页面所需的任何内容(包括选择列表的值).


例:

例如,在viewmodel上有一个属性来保存选择和一个包含可能值枚举的属性就足够了.像这样的东西:

public class MyViewModel
{
   ...

   public int SelectedId { get; set; }

   ...

   public IEnumerable<Choice> Choices { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的例子中,Choice是一个具有两个属性的类,一个包含一些标识符,另一个包含要显示的文本.像这样的东西:

public class Choice
{
   public int Id { get; set; }
   public string Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你可能只有一个DropDownListFor处理显示/选择工作的人.像这样的东西:

@model MyViewModel

@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.Choices, "Id", "Text"), "Choose... ")
Run Code Online (Sandbox Code Playgroud)

回到你的控制器的动作,视图模型SelectedId将填充相应的选择Id选项视图下拉列表.