码迷,mamicode.com
首页 > Web开发 > 详细

在ASP.NET MVC中实现Select多选

时间:2015-03-30 10:56:04      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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

 

实现效果如下:

技术分享

初始状态某些选项被选中。

 

当按着ctrl键,进行重新选择多项,点击"提交"按钮,把选中项的id拼接。
技术分享

 

对于Select中的项,包含显示值,Value值,以及是否选中,抽象成如下的类。

 

    public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
    }

 

对于整个多选Select来说,在ASP.NET MVC中,所有的选项被看作SelectListItem类型,选中的项是一个string类型的集合。于是多选Select的View Model设计为:

 

    public class CityVm
    {
        public IEnumerable<SelectListItem>  Cities { get; set; }
        public IEnumerable<string> SelectedCities { get; set; }
    }

 

在HomeController中,把SelectListItem的集合赋值给CityVm的Cities属性。

 

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var cities = new List<City>
            {
                new City(){Id = 1, Name = "青岛", IsSelected = true},
                new City(){Id = 2, Name = "胶南", IsSelected = false},
                new City(){Id = 3, Name = "即墨", IsSelected = true},
                new City(){Id = 4, Name = "黄岛", IsSelected = false},
                new City(){Id = 5, Name = "济南", IsSelected = false}
            };
            var citiesToPass = from c in cities
                select new SelectListItem() {Text = c.Name, Value = c.Id.ToString(),Selected = c.IsSelected};
            
            CityVm cityVm = new CityVm();
            cityVm.Cities = citiesToPass;
            ViewData["cc"] = citiesToPass.Count();
            return View(cityVm);
        }
        ......
    }    

 

在Home/Index.cshtml中,是一个CityVm的强类型视图,对于选中的项会以IEnumerable<string>集合传递给控制器。

 

@model MvcApplication1.Models.CityVm
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm("GetCities", "Home", FormMethod.Post, new {id = "myForm"}))
{   
    @Html.ListBoxFor(c => c.SelectedCities, Model.Cities, new {size = ViewData["cc"]})
    <br/>
    <input type="submit" value="提交"/>
}

 

在HomeController中,再把从视图传递过来的IEnumerable<string>拼接并呈现。

 

    public class HomeController : Controller
    {
        ......
        [HttpPost]
        public ActionResult GetCities(IEnumerable<string> selectedCities)
        {
            if (selectedCities == null)
            {
                return Content("没有选中任何选项");
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("选中项的Id是:" + string.Join(",", selectedCities));
                return Content(sb.ToString());
            }
        }
    }    

在ASP.NET MVC中实现Select多选

标签:

原文地址:http://www.cnblogs.com/darrenji/p/4377157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!