zoukankan      html  css  js  c++  java
  • ASP.NET MVC 3.0 知识记要(2)【RadioButtonList、CheckBoxList】

    实践五.呈现RadioButtonList

      1.假如现在从数据库提取了一些数据:

    List<Category> cateoryList = new List<Category>()
    {
    new Category(){
    CategoryID = 1,
    CategoryName = "公司内造"
    },
    new Category(){
    CategoryID = 2,
    CategoryName = "公司外购"
    }
    };

      

      2.通过Linq 将数据生成 SelectListItem 类型的集合,并赋予 ViewData["CategoryID"]

    ViewData["CategoryID"] = (from item in cateoryList
    select new SelectListItem()
    {
    Value = item.CategoryID.ToString(),
    Text = item.CategoryName
    }).ToList();

    一定要调用 ToList(),否则会因为延迟查询而导致将 空ViewData["CategoryID"]被传入View层。

      3.在View层顶端,可以将 ViewData赋予本地变量

    @{
    List<SelectListItem> CategoryItems = ViewData["CategoryID"] as List<SelectListItem>;
    }

      

      4.遍历集合生成 Radio出来:生成原生的HTML,

    注意:radio的name 与 ViewData的键名相同。

    for (int i = 0; i < @CategoryItems.Count; i++)
    {
    var isChecked = "";
    SelectListItem item = @CategoryItems[i];
    if (item.Selected == true)
    {
    isChecked = "checked = 'checked'";
    }

    <input type="radio" id="@string.Format("CategoryID_{0}", @i)" name="CategoryID" value="@item.Value" @isChecked />
    <label for="@string.Format("CategoryID_{0}", @i)">@item.Text</label>
    }


    实践六. 呈现 CheckBoxList

      步骤分5步,前3步与上面一模一样,这里只说后面步骤:

      4.类型肯定是 checkbox;因为多选框本质是对一个集合的勾选,所以name可以适当以复数形式表现

    for (int i = 0; i < @CategoryItems.Count; i++)
    {
    var isChecked = "";
    SelectListItem item = @CategoryItems[i];
    if (item.Selected == true)
    {
    isChecked = "checked = 'checked'";
    }

    <input type="checkbox" id="@string.Format("CategoryID_{0}", @i)" name="CategoryIDs" value="@item.Value" @isChecked />
    <label for="@string.Format("CategoryID_{0}", @i)">@item.Text</label>
    }

      5.基于Post请求的Action之参数,不妨添加一个 字符串数组,其名称与checkBox的name相同

    [HttpPost]
    public void EditOrder(Order order, string[] CategoryIDs)
    {

    }

    对于包含着基础的string类型、int类型的属性,只要在基于Post请求的Action之参数中有同名出现,那么值就会被赋予其上,包括Order类里的属性也会被赋上值,尽管这看起来有些重复:

    [HttpPost]
    public void EditOrder(Order order, string[] CategoryIDs, string Description)
    {

    }







  • 相关阅读:
    vue 设置全局变量、指定请求的 baseurl
    npm ERR! missing script: build
    npm install 报错,提示`gyp ERR! stack Error: EACCES: permission denied` 解决方法
    vue-cli 4 安装与 新建项目 路由
    PHP7安装redis扩展
    C#中的list的System.Predicate<in T>和System.Comparison<in T>的应用
    6个2教你认识递归的力量!
    C#中的预编译指令介绍[转]
    C#---数据库访问通用类、Access数据库操作类、mysql类 .[转]
    GOTO语句以及GOTO机制的模式实现
  • 原文地址:https://www.cnblogs.com/luoxiaonet/p/2368185.html
Copyright © 2011-2022 走看看