2011-03-29 86 views
2

我目前正在使用一个应用程序,在该应用程序中显示视图中列表框中的项目列表,然后将所选项目发送回控制器。ASP.NET MVC中的Html.ListBox需要帮助

我的模型如下:

 
public class Items 
    { 
     [DisplayName("Items")] 
     public string[] Items { get; set; } 
    } 

当用户第一次请求页面时,项目列表必须从数据库中查询并发送至视图。 我能弄清楚如何在控制器端将项目收集到ArrayList/string []中,但无法理解将视图与模型绑定在一起并使用Html.ListboxFor显示列表并返回模型的语法在表单上提交。

有人可以帮助我。

谢谢。

回答

8

查看模型:

public class MyViewModel 
{ 
    [DisplayName("Items")] 
    public string[] SelectedItemIds { get; set; } 
    public IEnumerable<SelectListItem> Items { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel 
     { 
      // preselect some items 
      // leave empty if you want none to be selected initially 
      SelectedItemIds = new[] { "1", "3" }, 

      // Normally you would fetch those from your database 
      // hardcoded here for the purpose of the post    
      Items = Enumerable.Range(1, 10).Select(x => new SelectListItem 
      { 
       Value = x.ToString(), 
       Text = " item " + x 
      }) 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(string[] selectedItemIds) 
    { 
     // here you will get the list of selected item ids 
     // where you could process them 
     // If you need to redisplay the same view make sure that 
     // you refetch the model items once again from the database 
     ... 

    } 
} 

视图(剃刀):

@model AppName.Models.MyViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(x => x.SelectedItemIds) 

    @Html.ListBoxFor(
     x => x.SelectedItemIds, 
     new SelectList(Model.Items, "Value", "Text") 
    ) 
    <input type="submit" value="OK" /> 
} 

视图(WebForms的):

<% using (Html.BeginForm()) { %> 
    <%= Html.LabelFor(x => x.SelectedItemIds) %> 

    <%= Html.ListBoxFor(
     x => x.SelectedItemIds, 
     new SelectList(Model.Items, "Value", "Text") 
    ) %> 
    <input type="submit" value="OK" /> 
<% } %>