• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[转]ASP.NETMVCSelectListExample

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文转自: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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.NET 2.0,无刷新页面新境界发布时间:2022-07-10
下一篇:
初学者的CKEditor ASP.NET控制集成指南发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap