2011-03-29 81 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" /> 
<% } %>