asp.net-mvc 如何在 MVC4 Razor 中使用 CheckBoxList 和 DropdownList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19468666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use CheckBoxList and DropdownList in MVC4 Razor
提问by Mahendra Sahu
I have to use @Html.CheckBoxListFor<> or @Html.DropdownListFor<>.I am confused about how to use these helper class in View whild I am using List for Model Binding.
我必须使用@Html.CheckBoxListFor<> 或@Html.DropdownListFor<>。我对如何在视图中使用这些帮助类感到困惑,而我正在使用列表进行模型绑定。
What is the Right and Easiest way to Bind List into CheckBoxList and DropdownList.
将 List 绑定到 CheckBoxList 和 DropdownList 的正确和最简单的方法是什么。
In Model:
在模型中:
public class SampleViewModel
{
public IEnumerable<Responsible> AvailableResponsibles { get; set; }
public IEnumerable<Responsible> SelectedResponsibles { get; set; }
public PostedResponsibles PostedResponsibles { get; set; }
Responsible objResponsible = new Responsible();
public SampleViewModel GetResponsiblesInitialModel()
{
//setup properties
var model = new SampleViewModel();
var selectedResponsibles = new List<Responsible>();
//setup a view model
model.AvailableResponsibles = objResponsible.GetAll().ToList();
model.SelectedResponsibles = selectedResponsibles;
return model;
}
}
public class Responsible
{
//Integer value of a checkbox
public int Id { get; set; }
//String name of a checkbox
public string Name { get; set; }
//Boolean value to select a checkbox
//on the list
public bool IsSelected { get; set; }
//Object of html tags to be applied
//to checkbox, e.g.:'new{tagName = "tagValue"}'
public object Tags { get; set; }
public IEnumerable<Responsible> GetAll()
{
return new List<Responsible> {
new Responsible {Name = "Apple", Id = 1 },
new Responsible {Name = "Banana", Id = 2},
new Responsible {Name = "Cherry", Id = 3},
new Responsible {Name = "Pineapple", Id = 4},
new Responsible {Name = "Grape", Id = 5},
new Responsible {Name = "Guava", Id = 6},
new Responsible {Name = "Mango", Id = 7}
};
}
}
public class PostedResponsibles
{
//this array will be used to POST values from the form to the controller
public string[] ResponsibleIds { get; set; }
}
And View Is:
和视图是:
<tr>
<td>
@Html.LabelFor(model=>model.Responsible)
</td>
<td>
@Html.CheckBoxListFor(model => model.PostedResponsibles.ResponsibleIds,
model => model.AvailableResponsibles,
Responsible => Responsible.Id,
Responsible => Responsible.Name,
model => model.SelectedResponsibles)
</td>
</tr>
Currently I am using Nuget Packege but it is little bit confusing and hard to use.Suggest me any other to achieve this one.
目前我正在使用 Nuget Packege,但它有点令人困惑且难以使用。建议我使用其他任何方法来实现这一目标。
采纳答案by HaBo
It depend on your UI requirement. if you need a drop down list then use that.
这取决于您的 UI 要求。如果您需要下拉列表,请使用它。
CheckBoxList is not out of the box helper, it is a custom helper.
CheckBoxList 不是开箱即用的助手,它是一个自定义助手。
You can find more details of the helper (CheckBoxList) from here Code Project
您可以从此处代码项目找到帮助程序 (CheckBoxList) 的更多详细信息
Regarding Drop down please refer to MSDN. It can be overloaded in multiple ways.
关于下拉请参考MSDN。它可以通过多种方式重载。
Here are the available ASP.NET MVC helpers
以下是可用的ASP.NET MVC 帮助程序
回答by Swapnil Malap
Step Install package using package manager
Install-Package MvcCheckBoxListAdd Fruit.cs
namespace CheckBoxListForApp.Models { public class Fruit { public int Id { get;set;} public string Name { get;set; } public bool IsSelected{get;set;} public object Tags { get;set;} } }Add FruitViewModel.cs
using System.Collections.Generic; namespace CheckBoxListForApp.Models { public class FruitViewModel { public IEnumerable<Fruit> AvailableFruits { get; set; } public IEnumerable<Fruit> SelectedFruits { get; set; } public PostedFruits PostedFruits { get; set; } } }Add PostedFruits.cs
namespace CheckBoxListForApp.Models { /// <summary> /// for Helper class to make posting back selected values easier /// </summary> public class PostedFruits { //this array will be used to POST values from the form to the controller public string[] FruitIds { get; set; } } }Add HomeController.cs
using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.Mvc; using CheckBoxListForApp.Models; namespace CheckBoxListForApp.Controllers { public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(GetFruitsInitialModel()); } [HttpPost] public ActionResult Index(PostedFruits postedFruits) { return View(GetFruitsModel(postedFruits)); } private FruitViewModel GetFruitsModel(PostedFruits postedFruits) { var model = new FruitViewModel(); var selectedFruits = new List<Fruit>(); var postedFruitIds = new string[0]; if (postedFruits == null) postedFruits = new PostedFruits(); // if a view model array of posted fruits ids exists // and is not empty,save selected ids if (postedFruits.FruitIds != null && postedFruits.FruitIds.Any()) { postedFruitIds = postedFruits.FruitIds; } // if there are any selected ids saved, create a list of fruits if (postedFruitIds.Any()) { selectedFruits = FruitRepository.GetAll() .Where(x => postedFruitIds.Any(s => x.Id.ToString().Equals(s))) .ToList(); } model.AvailableFruits = FruitRepository.GetAll().ToList(); model.SelectedFruits = selectedFruits; model.PostedFruits = postedFruits; return model; } private FruitViewModel GetFruitsInitialModel() { var model = new FruitViewModel(); var selectedFruits = new List<Fruit>(); model.AvailableFruits = FruitRepository.GetAll().ToList(); model.SelectedFruits = selectedFruits; return model; } } }Add FruitRepository.cs
using System.Collections.Generic; using System.Linq; namespace CheckBoxListForApp.Models { /// <summary> /// work as fruit repository /// </summary> public static class FruitRepository { /// <summary> /// for get fruit for specific id /// </summary> public static Fruit Get(int id) { return GetAll().FirstOrDefault(x => x.Id.Equals(id)); } /// <summary> /// for get all fruits /// </summary> public static IEnumerable<Fruit> GetAll() { return new List<Fruit> { new Fruit {Name = "Apple", Id = 1 }, new Fruit {Name = "Banana", Id = 2}, new Fruit {Name = "Cherry", Id = 3}, new Fruit {Name = "Pineapple", Id = 4}, new Fruit {Name = "Grape", Id = 5}, new Fruit {Name = "Guava", Id = 6}, new Fruit {Name = "Mango", Id = 7} }; } } }Add Index.cshtml
@using MvcCheckBoxList.Model @model CheckBoxListForApp.Models.FruitViewModel @{ ViewBag.Title = "Home Page"; } <section class="checkBoxListFor"> <p> <label>Please Select Fruits:</label> @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.CheckBoxListFor(model => model.PostedFruits.FruitIds, model => model.AvailableFruits, fruit => fruit.Id, fruit => fruit.Name, model => model.SelectedFruits, Position.Horizontal) <input class="green" type="submit" value="POST to Controller" /> } </p> </section>
步骤 使用包管理器安装包
Install-Package MvcCheckBoxList添加水果.cs
namespace CheckBoxListForApp.Models { public class Fruit { public int Id { get;set;} public string Name { get;set; } public bool IsSelected{get;set;} public object Tags { get;set;} } }添加FruitViewModel.cs
using System.Collections.Generic; namespace CheckBoxListForApp.Models { public class FruitViewModel { public IEnumerable<Fruit> AvailableFruits { get; set; } public IEnumerable<Fruit> SelectedFruits { get; set; } public PostedFruits PostedFruits { get; set; } } }添加PostedFruits.cs
namespace CheckBoxListForApp.Models { /// <summary> /// for Helper class to make posting back selected values easier /// </summary> public class PostedFruits { //this array will be used to POST values from the form to the controller public string[] FruitIds { get; set; } } }添加HomeController.cs
using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.Mvc; using CheckBoxListForApp.Models; namespace CheckBoxListForApp.Controllers { public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(GetFruitsInitialModel()); } [HttpPost] public ActionResult Index(PostedFruits postedFruits) { return View(GetFruitsModel(postedFruits)); } private FruitViewModel GetFruitsModel(PostedFruits postedFruits) { var model = new FruitViewModel(); var selectedFruits = new List<Fruit>(); var postedFruitIds = new string[0]; if (postedFruits == null) postedFruits = new PostedFruits(); // if a view model array of posted fruits ids exists // and is not empty,save selected ids if (postedFruits.FruitIds != null && postedFruits.FruitIds.Any()) { postedFruitIds = postedFruits.FruitIds; } // if there are any selected ids saved, create a list of fruits if (postedFruitIds.Any()) { selectedFruits = FruitRepository.GetAll() .Where(x => postedFruitIds.Any(s => x.Id.ToString().Equals(s))) .ToList(); } model.AvailableFruits = FruitRepository.GetAll().ToList(); model.SelectedFruits = selectedFruits; model.PostedFruits = postedFruits; return model; } private FruitViewModel GetFruitsInitialModel() { var model = new FruitViewModel(); var selectedFruits = new List<Fruit>(); model.AvailableFruits = FruitRepository.GetAll().ToList(); model.SelectedFruits = selectedFruits; return model; } } }添加FruitRepository.cs
using System.Collections.Generic; using System.Linq; namespace CheckBoxListForApp.Models { /// <summary> /// work as fruit repository /// </summary> public static class FruitRepository { /// <summary> /// for get fruit for specific id /// </summary> public static Fruit Get(int id) { return GetAll().FirstOrDefault(x => x.Id.Equals(id)); } /// <summary> /// for get all fruits /// </summary> public static IEnumerable<Fruit> GetAll() { return new List<Fruit> { new Fruit {Name = "Apple", Id = 1 }, new Fruit {Name = "Banana", Id = 2}, new Fruit {Name = "Cherry", Id = 3}, new Fruit {Name = "Pineapple", Id = 4}, new Fruit {Name = "Grape", Id = 5}, new Fruit {Name = "Guava", Id = 6}, new Fruit {Name = "Mango", Id = 7} }; } } }添加Index.cshtml
@using MvcCheckBoxList.Model @model CheckBoxListForApp.Models.FruitViewModel @{ ViewBag.Title = "Home Page"; } <section class="checkBoxListFor"> <p> <label>Please Select Fruits:</label> @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.CheckBoxListFor(model => model.PostedFruits.FruitIds, model => model.AvailableFruits, fruit => fruit.Id, fruit => fruit.Name, model => model.SelectedFruits, Position.Horizontal) <input class="green" type="submit" value="POST to Controller" /> } </p> </section>

