• MVC通过UIHint和自定义视图显示RadioButtonList


    在Product类中有一个显示删除状态的属性DelFlag,在编辑视图页,对于所有的删除状态以RadioButtonList显示出来,如果RadioButtonList选项的value值与当前model的DelFlag属性值相同,则勾选该选项,如图:

    1

    思路:

    →在Views/Shared/EditorTemplates/RadioButtonList.chtml部分视图以RadioButtonList呈现所有删除状态。
    →在编辑视图中,需要把有关删除状态,封装成List<SelectListItem>放在路由中传递给部分视图RadioButtonList.chtml
    →在Product的DelFlag属性上,通过[UIHint("RadioButtonList")]指定该属性的显示视图

        public class Product
        {
            [UIHint("RadioButtonList")]
            public int? DelFlag { get; set; }
        }

    HomeController:

        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View( new Product(){DelFlag = 2});
            }

        }

    Home/Index.cshtml视图:

    其中,关于删除状态,封装成List<SelectListItem>,并通过路由传递给接收的部分视图。

    @model MvcApplication2.Models.Product
     
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
        
        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem(){Text = "正常使用",Value = "1"});
        list.Add(new SelectListItem() { Text = "逻辑删除", Value = "2" });
        list.Add(new SelectListItem() { Text = "物理删除", Value = "3" });
    }
     
    <style type="text/css">
        ul{
            list-style-type: none;
        }
    </style>
     
    <h2>Index</h2>
     
    @Html.EditorFor(model => model.DelFlag, new {lst = list})

    Views/Shared/EditorTemplates/RadioButtonList.chtml部分视图:

    @model int?
     
    @{
        var list = (List<SelectListItem>)ViewData["lst"]; 
    }
     
    <ul>
        @foreach (var item in list)
        {
            <li>
                @{
                    var radioId = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value); //DelFlag_1 DelFlag_2 DelFlag_3 
                    var checkedCls =
                        (item.Value == Model.ToString() ? "Checked" : string.Empty);
                        
                    //name=DelFlag 属性名称被保存在ViewData.TemplateInfo.HtmlFieldPrefix中
                    <input type="radio" id="@radioId" name="@ViewData.TemplateInfo.HtmlFieldPrefix" value="@item.Value" checked="@checkedCls"/>
                    <label for="@radioId">@item.Text</label>
                }
            </li>
        }
    </ul>
  • 相关阅读:
    Android自己主动升级框架
    一句话说清楚啥是delegate
    C#
    MySQL Community Server 5.6和MySQL Installer 5.6
    仿htc sense的弹性listView!
    双向队列(STL做法)
    余承东:未来5年中国大部分智能手机厂商消失
    P3808 【模版】AC自动机(简单版)
    P1103 书本整理
    P2580 于是他错误的点名开始了
  • 原文地址:https://www.cnblogs.com/darrenji/p/3755336.html
Copyright © 2020-2023  润新知