zoukankan      html  css  js  c++  java
  • asp.net mvc 下拉列表

    第一步:新建一个格式化下拉列表的公共类文件

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    
    namespace GmkGM.Infrastructure
    {
        public class Common
        {
            /// <summary>
            /// 获取下拉列表(有层级结构)
            /// </summary>
            /// <param name="Id"></param>
            /// <returns></returns>
            public static IList<SelectListItem> GetDropdownList(IList listInfo,int? Id,string name)
            {
                DataTable ds = Common.ToDataSet(listInfo).Tables[0];
    
                if (null != ds && ds.Rows.Count > 0)
                {
                    //添加一列
                    ds.Columns.Add("Level", typeof(int));
                    // 克隆dt 的结构,包括所有 dt 架构和约束,并无数据
                    DataTable newDT = ds.Clone();
                    DataTable catelist = Common.GetTreeList(ds, newDT, 0, 0);
                    if (catelist.Rows.Count > 0)
                    {
                        IList<SelectListItem> list = new List<SelectListItem>();
                        foreach (DataRow row in catelist.Rows)
                        {
                            SelectListItem item = new SelectListItem();
                            item.Value = Convert.ToString(row["ID"]);
                            string pri = "----";
                            var rt = row["Level"];
                            item.Text = row[name] == DBNull.Value ? string.Empty : Common.StringRepeat(pri, Convert.ToInt32(row["Level"]) + 1) + Convert.ToString(row[name]);
    
                            if (Id == Convert.ToInt32(item.Value))
                            {
                                item.Selected = true;
                            }
    
                            list.Add(item);
                        }
                        SelectListItem first = new SelectListItem();
                        first.Text = "--父类--";
                        first.Value = "0";
                        list.Insert(0, first);
                        return list;
                    }
                }
                return null;
            }
    //无层级结构
    public static IList<SelectListItem> GetDropdownList2(IList listInfo, int? Id, string name) { if (listInfo.Count > 0) { DataTable ds = Common.ToDataSet(listInfo).Tables[0]; if (null != ds && ds.Rows.Count > 0) { IList<SelectListItem> list = new List<SelectListItem>(); foreach (DataRow row in ds.Rows) { SelectListItem item = new SelectListItem(); item.Value = Convert.ToString(row["ID"]); item.Text = row[name] == DBNull.Value ? string.Empty : Convert.ToString(row[name]); if (Id == Convert.ToInt32(item.Value)) { item.Selected = true; } list.Add(item); } SelectListItem first = new SelectListItem(); first.Text = "--父类--"; first.Value = "0"; list.Insert(0, first); return list; } return null; } return null; } /// <summary> /// 生成树形结构 /// </summary> /// <param name="dt">数据源表</param> /// <param name="newDT">返回的结果表</param> /// <param name="Pid">父类ID值</param> /// <param name="level">层级</param> /// <returns></returns> public static DataTable GetTreeList(DataTable dt, DataTable newDT, int Pid, int level = 0) { for (int i = 0; i < dt.Rows.Count; i++) { if (Convert.ToInt32(dt.Rows[i]["Pid"]) == Pid) { //用来标记这个分类是第几级的 dt.Rows[i]["Level"] = level; newDT.Rows.Add(dt.Rows[i].ItemArray); //找子分类 DataTable innerDT = GetTreeList(dt, newDT, Convert.ToInt32(dt.Rows[i]["Id"]), level + 1); } } return newDT; } /// <param name="str">字符串</param> /// <param name="n">重复次数</param> public static string StringRepeat(string str, int n) { if (String.IsNullOrEmpty(str) || n <= 0) return str; StringBuilder sb = new StringBuilder(); while (n > 0) { sb.Append(str); n--; } return sb.ToString(); } // list转换为DataSet public static DataSet ToDataSet(IList p_List) { DataSet result = new DataSet(); DataTable _DataTable = new DataTable(); if (p_List.Count > 0) { PropertyInfo[] propertys = p_List[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { _DataTable.Columns.Add(pi.Name, pi.PropertyType); } for (int i = 0; i < p_List.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { object obj = pi.GetValue(p_List[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); _DataTable.LoadDataRow(array, true); } } result.Tables.Add(_DataTable); return result; } /// <summary> /// 找出一个分类所有子分类的ID /// </summary> /// <param name="catId"></param> /// /// <returns></returns> public static DataTable GetChildren(DataTable dt, int catId) { //定义一个表存放保存找到的子分类的id DataTable newDT = new DataTable(); //添加一列 newDT.Columns.Add("CID", typeof(int)); if (dt != null && dt.Rows.Count > 0) { //循环所有的分类找子类 for (int i = 0; i < dt.Rows.Count; i++) { if (Convert.ToInt32(dt.Rows[i]["PID"]) == catId) { newDT.Rows.Add((Object)dt.Rows[i]["Id"]); //再找这个$v的子分类 GetChildren(dt, Convert.ToInt32(dt.Rows[i]["Id"])); } } } return newDT; } } }

     第二步:服务层调用

            public IList List2()
            {
                return db.Whse_Stock_List().ToList();
            }
    
            public IList<SelectListItem> GetProductDropdownList(int? Id)
            {
                return Common.GetDropdownList2(List2(), Id, "ProductName");
            }
    
            public IList List()
            {
                return db.Whse_Location_List().ToList();
            }
    
            public IList<SelectListItem> GetLocationDropdownList(int? Id)
            {
                return Common.GetDropdownList(List(), Id,"Code");
            }

    第三步:控制器调用

            // GET: Inventory/Create
            public ActionResult Create()
            {
                #region 产品下拉列表
                ViewBag.ProductTypes = new InventoryService().GetProductDropdownList(null);
                #endregion
    
                #region 仓库位置下拉列表
                ViewBag.LocationTypes = new InventoryService().GetLocationDropdownList(null);
                #endregion
    
                return View();
            }
            [ValidateAntiForgeryToken]
            [HttpPost]
            public ActionResult Create(Inventory model)
            {
                try
                {
                    #region 产品下拉列表
                    ViewBag.ProductTypes = new InventoryService().GetProductDropdownList(model.StockID);
                    #endregion
    
                    #region 仓库位置下拉列表
                    ViewBag.LocationTypes = new InventoryService().GetLocationDropdownList(model.LocationID);
                    #endregion
    
                    //验证模型是否有效
                    if (ModelState.IsValid)
                    {
                        bool res = new InventoryService().Insert(model);
                        if (!res)
                        {
                            TempData[LastMessageInfoKey.LastErrorMessageTempDataKey] = "创建失败!";
                            return View(model);
                        }
                        TempData[LastMessageInfoKey.LastSuccessMessageTempDataKey] = "创建成功!";
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return View(model);
                    }
                }
                catch (Exception ex)
                {
                    TempData[LastMessageInfoKey.LastErrorMessageTempDataKey] = ex.Message;
                    return View(model);
                }
            }
            // GET: Inventory/Edit/5
            public ActionResult Edit(int StockID, int LocationID)
            {
                InventoryModel Inventory = service.Get(StockID,LocationID);
    
                #region 产品下拉列表
                ViewBag.ProductTypes = new InventoryService().GetProductDropdownList(StockID);
                #endregion
    
                #region 仓库位置下拉列表
                ViewBag.LocationTypes = new InventoryService().GetLocationDropdownList(LocationID);
                #endregion
    
                return View(Inventory);
            }
    
            [ValidateAntiForgeryToken]
            [HttpPost]
            public ActionResult Edit(Inventory model)
            {
                try
                {
                    #region 产品下拉列表
                    ViewBag.ProductTypes = new InventoryService().GetProductDropdownList(model.StockID);
                    #endregion
    
                    #region 仓库位置下拉列表
                    ViewBag.LocationTypes = new InventoryService().GetLocationDropdownList(model.LocationID);
                    #endregion
    
                    //验证模型是否有效
                    if (ModelState.IsValid)
                    {
                        bool res = service.Update(model);
                        if (!res)
                        {
                            TempData[LastMessageInfoKey.LastErrorMessageTempDataKey] = "编辑失败!";
                            return View(model);
                        }
                        TempData[LastMessageInfoKey.LastSuccessMessageTempDataKey] = "编辑成功!";
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        return View(model);
                    }
                }
                catch (Exception ex)
                {
                    TempData[LastMessageInfoKey.LastErrorMessageTempDataKey] = ex.Message;
                    return View(model);
                }
            }

    第四步:前端页面调用

    @model GmkGM.Whse.Model.Inventory
    @{
        ViewBag.Title = "Create";
    }
    
    @section styles{
        @Styles.Render("~/bundles/form/css")
    }
    
    @section scripts{
        @Scripts.Render("~/bundles/form/js")
    }
    
    @using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.AntiForgeryToken()
    
        <div class="row">
            <div class="col-xs-12">
                <fieldset>
                    @Html.LabelFor(model => model.StockID)(必填)
                    @if (ViewBag.ProductTypes != null)
                    {
                        @Html.DropDownList("StockID", ViewBag.ProductTypes as IEnumerable<SelectListItem>, new { @class = "form-control" })
                    }
                    else
                    {
                        <select id="StockID" name="StockID" class="form-control"></select>
                    }
                </fieldset>
                <fieldset>
                    @Html.LabelFor(model => model.LocationID)(必填)
                    @if (ViewBag.LocationTypes != null)
                    {
                        @Html.DropDownList("LocationID", ViewBag.LocationTypes as IEnumerable<SelectListItem>, new { @class = "form-control" })
                    }
                    else
                    {
                        <select id="LocationID" name="LocationID" class="form-control"></select>
                    }
                </fieldset>
    
                <fieldset>
                    @Html.LabelFor(model => model.Balance)(必填)
                    @Html.EditorFor(model => model.Balance, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Balance, "", new { @Style = "color:red" })
                </fieldset>
            </div>
        </div>
        <div class="form-actions center">
            <button class="btn btn-sm btn-success" type="submit">
                提交
                <i class="ace-icon fa fa-arrow-right icon-on-right bigger-110"></i>
            </button>
    
            <a class="btn btn-sm btn-warning" href="@Url.Action("Index")">
                返回
                <i class="ace-icon fa fa-undo bigger-110"></i>
            </a>
        </div>
    }

  • 相关阅读:
    (selenium+python)_UI自动化02_元素定位
    (selenium+python)_UI自动化01_Mac下selenium环境搭建
    2019_Chrome和ChromeDriver对应关系
    charles_02_模拟弱网测试
    charles_01_打断点修改接口请求&返回数据
    Jmeter和LoadRunner的区别
    Linux 系统结构,nglinx
    jmeter,badboy,jar包文件 常数吞吐量计时器?
    863公司 linux软测题
    linux centOS 7 GUI安装
  • 原文地址:https://www.cnblogs.com/zouke1220/p/7462738.html
Copyright © 2011-2022 走看看