【问题标题】:Need help in Html.ListBox in ASP.NET MVC在 ASP.NET MVC 中的 Html.ListBox 中需要帮助
【发布时间】:2011-03-29 21:06:59
【问题描述】:

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

我的模型如下:

公共类项目 { [显示名称(“项目”)] 公共字符串 [] 项目 { 获取;放; } }

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

谁能帮帮我。

谢谢。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    查看模型:

    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" />
    <% } %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多