需要帮助ASP.NET MVC中的Html.ListBox

时间:2011-03-29 21:07:00

标签: asp.net-mvc

我目前正在开发一个应用程序,其中我在视图的列表框中显示项目列表,然后将所选项目发送回控制器。

我的模型如下:

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

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

有人可以帮帮我吗。

感谢。

1 个答案:

答案 0 :(得分: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" />
<% } %>