如何在 MVC4 Razor 中使用 CheckBoxList 和 DropdownList

2024-05-08

我必须使用 @Html.CheckBoxListFor 或 @Html.DropdownListFor。当我使用列表进行模型绑定时,我对如何在视图中使用这些帮助器类感到困惑。

将列表绑定到 CheckBoxList 和 DropdownList 的正确且最简单的方法是什么。

在模型中:

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; }
    }

视图是:

<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>

目前我正在使用 Nuget 包,但它有点令人困惑且难以使用。建议我使用其他包来实现这一目标。


  1. 步骤使用包管理器安装包

    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<Fruit> AvailableFruits { get; set; }
        public IEnumerable<Fruit> SelectedFruits { get; set; }
        public PostedFruits PostedFruits { get; set; }
      }
    }
    
  4. 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; }
        }
    }
    
  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<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;
            }
        }
    }
    
  6. 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}
                                };
            }
        }
    }
    
  7. Add 索引.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>
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MVC4 Razor 中使用 CheckBoxList 和 DropdownList 的相关文章

随机推荐

  • TryXXX 类似带有“out”参数的方法与返回可为空值类型的方法?

    我经常在 C 中看到这样的方法 进行可能会或可能不会给出结果的计算 bool TrySomething SomeType inputData out SomeOtherType result 为什么人们不使用这样的东西呢 Nullable
  • HashMap 无法转换为 java.lang.string

    我正在尝试从列表视图中获取值 列表视图由hashmap类型的数组列表设置 因此 如果我尝试获取字符串中的值 则会出现错误HashMap cannot be cast to java lang string 详细信息1 java packag
  • 不使用修剪方法从字符串中删除空格?

    给定的字符串是 家 甜蜜的家 如果用户输入模式为 0 那么 o p 应该是 home sweet home 如果用户输入模式为 1 那么 o p 应该是 Do this https stackoverflow com questions 5
  • Android Gradle 构建缓慢

    我试图找出为什么我们的 Gradle 构建如此缓慢 目前 每次您在不进行任何更改的情况下进行构建时 构建时间约为 45 秒 这是一个单模块项目 我已经打开了分析 大部分时间都花在了 app dexDebug 我们使用 Gradle 2 8
  • 如何在Python中连接两个整数?

    如何在Python中连接两个整数 例如 给定10 and 20 我想要一个返回值1020 将两者都转换为字符串 连接字符串 然后将结果转换回整数 z int str x str y
  • 从开放的 HTTP 流中读取数据

    我正在尝试使用 NET WebRequest WebResponse 类来访问 Twitter 流 API 此处 http stream twitter com spritzer json 我需要能够打开连接并从打开的连接中增量读取数据 目
  • PHP文件上传错误tmp_name为空

    我的文件上传遇到这个问题 我尝试在检查验证时上传 PDF 文件TMP NAME是空的 当我检查时 FILES document attach error 该值为 1 意味着存在错误 但当我尝试上传其他 PDF 文件时 它已成功上传 为什么其
  • CollapsingToolbarLayout setTitle() 不会更新,除非折叠

    使用新的设计库 我们应该在CollapsingToolbarLayout 不是Toolbar本身 至少在使用折叠工具栏时 但setTitle 仅在以下特定情况下更新标题 当 的时候CollapsingToolbarLayout还没有标题 此
  • 帮助理解 gluLookAt()

    想象一下你站在地上 抬头看着天空中的一个立方体 当你倾斜头部时 立方体就会移动 我试图在 iPhone 上使用 OpenGL ES 来复制这一点 方法是操纵相机的倾斜 同时查看围绕原点绘制的简单 3D 立方体 我正在使用gluLookAt
  • 如何使用 CocoaPods 正确安装 ReactiveCocoa?

    我很新ReactiveCocoa 我尝试安装ReactiveCocoa几天前通过CocoaPods 这是我的podFile platform ios 7 0 pod ReactiveCocoa 使用后pod install我这里有日志文件
  • 一旦组件被销毁,在 initComponent 函数中创建的存储是否会发生内存泄漏,或者这些存储是否会被垃圾收集?

    这是从另一个问题中衍生出来的一个问题 在 ExtJS 4 中具有相同视图并多次存储的最佳实践 https stackoverflow com questions 27333787 best practice to have the same
  • “GTLDriveFile”类型的值没有成员“downloadUrl”

    我正在关注这个tutorial https developers google com drive ios devguide files我正在尝试用 Swift 来做这件事 The file对象没有downloadUrl财产 我不明白为什么
  • 获取Python中匹配字符串的特定模式后出现的数字

    我想获取所有匹配的数字 仅数字示例 0012 22 或包含与其对应的某些文本 示例 RF332 的数字 该数字与提供的字符串列表匹配 代码中的 my list 带有数字的文本的显示格式类似于用一两个空格分隔 提供示例输入文件以供参考 这是输
  • has_many 关系的动态 class_name

    我正在尝试与动态 class name 属性建立 has many 关系 class Category lt ActiveRecord Base has many ads class name gt lambda return self i
  • 如何找到最长的回文子序列(不是它的长度)

    我想找出字符串中最长的回文子序列 我到处都找到了找出子序列长度的算法 并声明该算法也可以扩展以返回子序列 但我没有找到如何实现的 有人能解释一下我怎样才能得到序列吗 既然你提到了链接最长回文子序列 http www geeksforgeek
  • http压缩和url压缩有什么区别?

    查看 Web config 中的节点 我发现它允许 httpCompression 和 urlCompression 元素 两者有什么区别 我只想执行标准 gzip 我应该使用哪一个 url压缩指定what压缩和http压缩表示how进行压
  • Wix:动态添加功能

    我们正在使用 Wix 为我们的软件构建 msi 我们有一些要在目标机器上实现的组件 插件 每个客户端的插件都不同 我们想要做的是创建一个标准构建并修改 msi 包中的功能列表 有没有办法通过自定义操作动态更改功能列表 例如 从自定义操作中读
  • 夏令时规则更改是否使 C 运行时库失效?

    前段时间我整理了一个time基于库 可用于计算某人一年内的相对时间 我当时注意到 为了夏令时 它在两个方向上进行了一小时的轮班 我刚刚想到国会更改了夏令时规则 http aa usno navy mil faq docs daylight
  • 如何在 Express 中模拟中间件以跳过单元测试的身份验证?

    我在 Express 中有以下内容 index js var service require subscription service var auth require auth auth service var router expres
  • 如何在 MVC4 Razor 中使用 CheckBoxList 和 DropdownList

    我必须使用 Html CheckBoxListFor 或 Html DropdownListFor 当我使用列表进行模型绑定时 我对如何在视图中使用这些帮助器类感到困惑 将列表绑定到 CheckBoxList 和 DropdownList