How to use CheckBoxList and DropdownList in MVC4 Razor

后端 未结 2 1099
广开言路
广开言路 2021-01-17 00:37

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.

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 00:50

    1. Step Install package using package manager

      Install-Package MvcCheckBoxList
      
    2. Add 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;}
        }
      }
      
    3. Add FruitViewModel.cs

      using System.Collections.Generic;
      namespace CheckBoxListForApp.Models
      {
        public class FruitViewModel
        {
          public IEnumerable AvailableFruits { get; set; }
          public IEnumerable SelectedFruits { get; set; }
          public PostedFruits PostedFruits { get; set; }
        }
      }
      
    4. Add PostedFruits.cs

      namespace CheckBoxListForApp.Models
      {
          /// 
          /// for Helper class to make posting back selected values easier
          /// 
          public class PostedFruits
          {
              //this array will be used to POST values from the form to the controller
              public string[] FruitIds { get; set; }
          }
      }
      
    5. 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();
                  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();
      
      
                  model.AvailableFruits = FruitRepository.GetAll().ToList();
                  model.SelectedFruits = selectedFruits;
                  return model;
              }
          }
      }
      
    6. Add FruitRepository.cs

      using System.Collections.Generic;
      using System.Linq;
      
      namespace CheckBoxListForApp.Models
      {
          /// 
          /// work as fruit repository
          /// 
          public static class FruitRepository
          {
              /// 
              /// for get fruit for specific id
              /// 
              public static Fruit Get(int id)
              {
                  return GetAll().FirstOrDefault(x => x.Id.Equals(id));
              }
      
              /// 
              /// for get all fruits
              /// 
              public static IEnumerable GetAll()
              {
                  return new List {
                                    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}
                                  };
              }
          }
      }
      
    7. Add Index.cshtml

      @using MvcCheckBoxList.Model
      @model CheckBoxListForApp.Models.FruitViewModel
      
      @{
          ViewBag.Title = "Home Page";
      }
      
      

      @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) }

提交回复
热议问题