我们知道,在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());
            }
        }
    }

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对阿兔在线工具的支持。如果你想了解更多相关内容请查看下面相关链接

点赞(0)

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部