本文转自:http://www.aspnetmvcninja.com/views/asp-net-mvc-select-list-example

Select lists are a great way to allow users to select multiple options from a long list of possible values. But how do you implement a select list in ASP.NET MVC? Luckily ASP.NET MVC does most of the heavy lifting for you. For this example I’m going to use a product that has multiple categories.

I’ll start by defining two model classes. The first class is called Category and I’ll use a list of them to store the possible values that will be displayed in the select list. For this example I’ll manually populate these in the controller but you could just as easily load them from a database. The other class is Product which has many category ID’s stored in the CategoryID property (a collection of int’s).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace MvcApplication2.Models
{
    public class Category
    {
        public int ID { get; set; }
 
        public string Name { get; set; }
    }
 
    public class Product
    {
        public ICollection<int> CategoryID { get; set; }
 
        public Product()
        {
            CategoryID = new List<int>();
        }
    }
}

Next we need a controller.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        private List<Category> GetOptions()
        {
            List<Category> categories = new List<Category>();
            categories.Add(new Category() { ID = 1, Name = "Bikes" });
            categories.Add(new Category() { ID = 2, Name = "Cars" });
            categories.Add(new Category() { ID = 3, Name = "Trucks" });
 
            return categories;
        }
 
        public ActionResult Index()
        {
            Product product = new Product();
            ViewBag.Categories = GetOptions();
            return View(product);
        }
 
        [HttpPost]
        public ActionResult Index(Product product)
        {
            ViewBag.Categories = GetOptions();
            return View(product);
        }
    }
}

I’ve created a private method called GetOptions() to populate a list with the categories. In real world applications you’ll have a service (business logic) class that provides these.

GET requests are handled by the first Index action. It passes the select list options to the view using the ViewBag. You could use ViewData just as easily. It also creates a new Product which becomes the model for the view. If you want to pre-select values then simply add them as follows:

1
2
product.CategoryID.Add(1);
product.CategoryID.Add(3);

The second Index action handles POST requests. The values for product are populated by the default binder that comes with ASP.NET MVC. This will add all of the values the user selected on the form so you don’t need to do anything.

Finally I have a view that displays the selected values as an unordered list with a select list below it allowing you to change the selected options.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Product>" %>
 
<!DOCTYPE html>
 
<html>
<head runat="server">
    <title>ASP.NET MVC Select List Example</title>
    <link type="text/css" href="../../Content/Site.css" rel="Stylesheet" />
</head>
<body>
    <div>
 
<h1>Select Values</h1>
<ul>
<% foreach (int c in Model.CategoryID)
   { %>
   <li><%: c %></li>
<% } %>
</ul>
<%: Html.DisplayForModel() %>
 
<h1>Change Values</h1>
<% using (Html.BeginForm())
   { %>
   <%: Html.ListBoxFor(x => x.CategoryID, new MultiSelectList(ViewBag.Categories, "ID", "Name", Model.CategoryID)) %>
   <br />
   <input type="submit" value="Submit" />
<% } %>
    </div>
</body>
</html>

In the view I’m using the Html.ListBoxFor() helper to render the select list. The second value passed to this is a list of options which I’m building using the MultiSelectList class. The constructor I’m using accepts 4 parameters:

  1. A list of options. In our example it’s List<Category>.
  2. The name of the property that contains the value used in the select list. I’m using “ID” here because I want to use the ID property of Category.
  3. The name of the property the contains the text to use for each option. I’m using “Name” here because I want to use the Name property of Category.
  4. A list of currently select values.

You may be wondering why I pass a list of Category objects to the view instead of creating the MultiSelectList in the controller and then passing that to the view. Personally I find creating the MultiSelectList in the controller both makes the controller more complicated and mixes view logic with controller logic. I also find this approach works better in real world applications where you are probably getting the list of options from a service class. By doing it this way it’s possible to mock the service and test that the value returned by the service class is passed to the view correctly when writing unit tests.

Here’s what it looks like when you first display the select list…

… and after you’ve selected some values

- See more at: http://www.aspnetmvcninja.com/views/asp-net-mvc-select-list-example#sthash.bzAba6tW.dpuf

[转]ASP.NET MVC Select List Example的更多相关文章

  1. ASP.NET MVC Select无限级分类选择下拉框

    1:读取父级下的所有子类别 *ViewBag.ParentItemList:不能与ParentId相同 private void ParentDropDownList() { List<SAS. ...

  2. asp.net mvc select用法

    var statusSelectItems = new List<SelectListItem> { "}, "}, "}, "}, "} ...

  3. 在ASP.NET MVC中实现Select多选

    我们知道,在ASP.NET MVC中实现多选Select的话,使用Html.ListBoxFor或Html.ListBox方法就可以.在实际应用中,到底该如何设计View Model, 控制器如何接收 ...

  4. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库

    在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...

  5. ASP.NET MVC开发:Web项目开发必备知识点

    最近加班加点完成一个Web项目,使用Asp.net MVC开发.很久以前接触的Asp.net开发还是Aspx形式,什么Razor引擎,什么MVC还是这次开发才明白,可以算是新手. 对新手而言,那进行A ...

  6. 【第三篇】ASP.NET MVC快速入门之安全策略(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  7. ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库

    前段时间在园子里看到了小蝶惊鸿 发布的有关绿色版的Linux.NET——“Jws.Mono”.由于我对.Net程序跑在Linux上非常感兴趣,自己也看了一些有关mono的资料,但是一直没有时间抽出时间 ...

  8. 使用Metrics.NET 构建 ASP.NET MVC 应用程序的性能指标

    通常我们需要监测ASP.NET MVC 或 Web API 的应用程序的性能时,通常采用的是自定义性能计数器,性能计数器会引发无休止的运维问题(损坏的计数器.权限问题等).这篇文章向你介绍一个新的替代 ...

  9. 你从未知道如此强大的ASP.NET MVC DefaultModelBinder

    看到很多ASP.NET MVC项目还在从request.querystring或者formContext里面获取数据,这实在是非常落后的做法.也有的项目建了大量的自定义的modelbinder,以为很 ...

随机推荐

  1. jQuery mobile 核心功能

    原文地址:http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/about/features.html 基于 jQuery 核心,使用和jQue ...

  2. 【树莓PI】下载机

    sudo app-get install ntfs-3g  读写ntfs格式的磁盘 mount -t ntfs /dev/sda4 /mnt/usb -o nls=utf8,umask=0 fdisk ...

  3. 十款PHP开发框架对比

    PHP开发框架近来在PHP社区中成为讨论的热点,几乎每天都在推出新的框架.面对市面上超过四十种的开发框架,你很难判断究竟哪一款最适合你,尤其是在这些框架所提供的功能不尽相同的时候.    本文将引导你 ...

  4. vector(相对线程安全) arryList(线程不安全)

    1.什么是线程安全? 如果说某个集合是线程安全的,那么我们就不用考虑并发访问这个集合?(需要定义自己百度,但是很难懂) 2.深入jvm中的线程安全的级别. a不变模式(String等基本类型) b.绝 ...

  5. ubuntu修改主机名和出现问题

    修改主机名方法,修改/etc/hostname即可,但是修改完成后,每次sudo都出现警告,警告解决方法如下: Linux 环境, 假设这台机器名字叫dev(机器的hostname), 每次执行sud ...

  6. oracle触发器学习

    转自:http://blog.csdn.net/indexman/article/details/8023740/ 本篇主要内容如下: 8.1 触发器类型 8.1.1 DML触发器 8.1.2 替代触 ...

  7. 容斥原理——uva 10325 The Lottery

    首先推荐一篇介绍容斥原理很好的博客http://www.cppblog.com/vici/archive/2011/09/05/155103.html 题意:求1~n中不能被给定m个数中任意一个数整除 ...

  8. 【Linux 命令】Linux系统下强制用户下线——who,pkill

    [日期]2014年11月18日 [平台]Centos 6.5 [工具]who pkill [步骤] 1)准备工作 以root身份登录. 2)执行who命令,查看有哪些用户已登录到当前主机

  9. 【Hadoop代码笔记】通过JobClient对Jobtracker的调用详细了解Hadoop RPC

    Hadoop的各个服务间,客户端和服务间的交互采用RPC方式.关于这种机制介绍的资源很多,也不难理解,这里不做背景介绍.只是尝试从Jobclient向JobTracker提交作业这个最简单的客户端服务 ...

  10. 在Visual Studio中利用NTVS创建Pomelo项目

    刚看新闻,才知道微软发布了Node.js Tools for Visual Studio(NTVS),受够了WebStorm输入法Bug的困扰,这下终于可以解脱了.以Pomelo为例,运行命令:pom ...