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[]; if (null != ds && ds.Rows.Count > )
{
//添加一列
ds.Columns.Add("Level", typeof(int));
// 克隆dt 的结构,包括所有 dt 架构和约束,并无数据
DataTable newDT = ds.Clone();
DataTable catelist = Common.GetTreeList(ds, newDT, , );
if (catelist.Rows.Count > )
{
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"]) + ) + Convert.ToString(row[name]); if (Id == Convert.ToInt32(item.Value))
{
item.Selected = true;
} list.Add(item);
}
SelectListItem first = new SelectListItem();
first.Text = "--父类--";
first.Value = "";
list.Insert(, first);
return list;
}
}
return null;
}
//无层级结构
public static IList<SelectListItem> GetDropdownList2(IList listInfo, int? Id, string name)
{
if (listInfo.Count > )
{
DataTable ds = Common.ToDataSet(listInfo).Tables[]; if (null != ds && ds.Rows.Count > )
{
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 = "";
list.Insert(, 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 = )
{
for (int i = ; 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 + );
}
}
return newDT;
} /// <param name="str">字符串</param>
/// <param name="n">重复次数</param>
public static string StringRepeat(string str, int n)
{
if (String.IsNullOrEmpty(str) || n <= )
return str;
StringBuilder sb = new StringBuilder();
while (n > )
{
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 > )
{
PropertyInfo[] propertys = p_List[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
_DataTable.Columns.Add(pi.Name, pi.PropertyType);
} for (int i = ; 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 > )
{
//循环所有的分类找子类
for (int i = ; 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>
}


asp.net mvc 下拉列表的更多相关文章
- ASP.NET MVC 下拉列表使用小结
ASP.NET MVC中下拉列表的用法很简单,也很方便,具体来说,主要是页面上支持两种Html帮助类的方法:DropDownList()和DropDownListFor().这篇博文主要作为个人的一个 ...
- ASP.NET MVC 下拉列表实现
https://blog.csdn.net/Ryan_laojiang/article/details/75349555?locationNum=10&fps=1 前言 我们今天开始好好讲讲关 ...
- ASP.NET MVC下使用AngularJs语言(六):获取下拉列表的value和Text
前面Insus.NET有在Angularjs实现DropDownList的下拉列表的功能.但是没有实现怎样获取下拉列表的value和text功能. 下面分别使用ng-click和ng-change来实 ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点
在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...
- 翻译:使用 ASP.NET MVC 4, EF, Knockoutjs and Bootstrap 设计和开发站点 - 3
原文地址:http://ddmvc4.codeplex.com/ 原文名称:Design and Develop a website using ASP.NET MVC 4, EF, Knockout ...
- ASP.NET MVC 5 05 - 视图
PS: 唉,这篇随笔国庆(2015年)放假前几天开始的,放完假回来正好又赶上年底,公司各种破事儿. 这尼玛都写跨年了都,真服了.(=_=#) 好几次不想写了都. 可是又不想浪费这么多,狠不下心删除.没 ...
- ASP.NET MVC 初体验
MVC系列文章终于开始了,前段时间公司项目结束后一直在封装一个html+ashx+js+easyui的权限系统,最近差不多也完成了,迟些时候会分享源码给大家.当然这个MVC系列结束后如果时间允许还会另 ...
- 【第四篇】ASP.NET MVC快速入门之完整示例(MVC5+EF6)
目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...
随机推荐
- 封装一个通过class获取元素的方法--我的JS原生库(1)
function getByClass(oParent,sClass){ var aEle = oParent.getElementsByTagName('*'); var result = []; ...
- [动态规划]P1378 油滴扩展
题目描述 在一个长方形框子里,最多有N(0≤N≤6)个相异的点,在其中任何一个点上放一个很小的油滴,那么这个油滴会一直扩展,直到接触到其他油滴或者框子的边界.必须等一个油滴扩展完毕才能放置下一个油滴. ...
- 记一次改造react脚手架的过程
公司突然组织需要重新搭建一个基于node的论坛系统,前端采用react,上网找了一些脚手架,或多或少不能满足自己的需求,最终在基于YeoMan的react脚手架generator-react-webp ...
- Django框架中的model(操作数据库)
什么是ORM ORM,即Object-Relational Mapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在具体的操作业务对象的时候,就不需要再去和复 ...
- zzuli 1816: 矩形 排序思维
1816: 矩形 Time Limit: 1 Sec Memory Limit: 128 MB Submit: 179 Solved: 54 SubmitStatusWeb Board Descr ...
- 用Redis轻松实现秒杀系统
秒杀系统的架构设计 秒杀系统,是典型的短时大量突发访问类问题.对这类问题,有三种优化性能的思路: 写入内存而不是写入硬盘 异步处理而不是同步处理 分布式处理 用上这三招,不论秒杀时负载多大,都能轻松应 ...
- Linux中nginx手动安装
本分类下有一个环境一键安装.那这背后发生了什么呢?咱们手动使用源码进行安装. 1.首先保证有一个能联网的centos. 2.百度 ningx 官网 点download http://nginx. ...
- [PHP基础]有关isset empty 函数的面试题
用isset()和empty()判断下面的变量. $str = ''; $int = 0 ; $arr = array(); isset($str) 返回的是 true 还是 false empty( ...
- jQuery选取所有复选框被选中的值并用Ajax异步提交数据
昨天和朋友做一个后台管理系统项目的时候涉及到复选框批量操作,如果用submit表单提交挺方便的,但是要实现用jQuery结合Ajax异步提交数据就有点麻烦了,因为我之前做过的项目中基本上没用Ajax来 ...
- Web 动画帧率(FPS)计算
我们知道,动画其实是由一帧一帧的图像构成的.有 Web 动画那么就会存在该动画在播放运行时的帧率.而帧率在不同设备不同情况下又是不一样的. 有的时候,一些复杂或者重要动画,我们需要实时监控它们的帧率, ...