先上图吧
你得先下载一个EasyUi框架,地址:http://www.jeasyui.net/download/
在你的项目中需要引用,前台代码如下:
DataGrid.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>DDL</title> <link href="../../Scripts/JqueryEasyUi/themes/default/easyui.css" rel="stylesheet" type="text/css" /> <link href="../../Scripts/JqueryEasyUi/themes/icon.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/JqueryEasyUi/jquery.min.js" type="text/javascript"></script> <script src="../../Scripts/FormatDate.js" type="text/javascript"></script> <script src="../../Scripts/JqueryEasyUi/jquery.easyui.min.js" type="text/javascript"></script> <script src="../../Scripts/datagrid.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $(‘#List2‘).datagrid({ title: ‘新闻列表‘, url: ‘DataGrid_Bind‘, method: ‘get‘, //默认是post,不允许对静态文件访问 width: ‘100%‘, iconCls: ‘icon-save‘, dataType: "json", fitColumns: true, rownumbers: true, //是否加行号 pagination: true, //是否显式分页 pageSize: 5, //页容量,必须和pageList对应起来,否则会报错 pageNumber: 1, //默认显示第几页 pageList: [5, 10, 15, 30, 45], //分页中下拉选项的数值 columns: [[ { field: ‘ck‘, checkbox: true }, { field: ‘Title‘, title: ‘标题‘ }, { field: ‘AddUser‘, title: ‘添加人‘ }, { field: ‘Content‘, title: ‘内容‘ }, { field: ‘AddDate‘, title: ‘添加日期‘, formatter: formatDateBoxFull }//这是设置日期的格式 ]], toolbar: [{ text: ‘添加‘, iconCls: ‘icon-add‘, handler: function () { // openDialog("add_dialog", "add"); alert("123"); } }, ‘-‘, { text: ‘修改‘, iconCls: ‘icon-edit‘, handler: function () { openDialog("add_dialog", "edit"); } }, ‘-‘, { text: ‘删除‘, iconCls: ‘icon-remove‘, handler: function () { delAppInfo(); } }], singleSelect: false, //允许选择多行 selectOnCheck: true, //true勾选会选择行,false勾选不选择行, 1.3以后有此选项 checkOnSelect: true, //true选择行勾选,false选择行不勾选, 1.3以后有此选项 collapsible: true }); }); </script> </head> <body> <div> <div style="margin: 10px 0;"> </div> <table id="List2" class="easyui-datagrid"> </table> </div> </body> </html>
这是设置日期格式的js代码,FormatDate.js:
/*该方法使日期列的显示符合阅读习惯*/ //datagrid中用法:{ field:‘StartDate‘,title:‘开始日期‘, formatter: formatDatebox, width:80} function formatDatebox(value) { if (value == null || value == ‘‘) { return ‘‘; } var dt = parseToDate(value); return dt.format("yyyy-MM-dd"); } /*转换日期字符串为带时间的格式*/ function formatDateBoxFull(value) { if (value == null || value == ‘‘) { return ‘‘; } var dt = parseToDate(value); return dt.format("yyyy-MM-dd");//设置前台显示的日期格式 } //辅助方法(转换日期) function parseToDate(value) { if (value == null || value == ‘‘) { return undefined; } var dt; if (value instanceof Date) { dt = value; } else { if (!isNaN(value)) { dt = new Date(value); } else if (value.indexOf(‘/Date‘) > -1) { value = value.replace(/\/Date\((-?\d+)\)\//, ‘$1‘); dt = new Date(); dt.setTime(value); } else if (value.indexOf(‘/‘) > -1) { dt = new Date(Date.parse(value.replace(/-/g, ‘/‘))); } else { dt = new Date(value); } } return dt; } //为Date类型拓展一个format方法,用于格式化日期 Date.prototype.format = function (format) //author: meizz { var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": this.getHours(), //hour "m+": this.getMinutes(), //minute "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() //millisecond }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; };
控制层代码:
NewsControl.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using NewsMvc.Models; using System.Text; namespace NewsMvc.Controllers { public class NewsController : Controller { BaseOption<News> bs = new BaseOption<News>(); News ns = new News(); public ActionResult Index() { return View(bs.getlist(ns)); } public ActionResult DDL() { return View(); } NewsDbContent db = new NewsDbContent(); public ActionResult DataGrid() { return View(); } public ActionResult DataGrid_Bind() { int pageSize = 5; int pageIndex = 1; int.TryParse(this.Request["page"], out pageIndex); int.TryParse(this.Request["rows"], out pageSize); pageSize = pageSize <= 0 ? 5 : pageSize; pageIndex = pageIndex < 1 ? 1 : pageIndex; var query = from u in db.Newss select u; var currentData = db.Newss.OrderBy(n => n.Id).Skip<News>((pageIndex - 1) * pageSize).Take(pageSize); //匿名类 var data = new { total = query.Count(), rows = currentData }; return Json(data, JsonRequestBehavior.AllowGet); } //添加 public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(News ns) { ns.Title = Request.Form["news_title"].ToString().Trim(); ns.AddUser = Request.Form["news_adduers"].ToString().Trim(); ns.Content = Request.Form["news_content"].ToString().Trim(); ns.AddDate = DateTime.Parse(Request.Form["news_adddate"].ToString().Trim()); bs.Add(ns); return RedirectToAction("Index"); } //编辑 public ActionResult Edit(int id) { ns = bs.FindById(id); return View(ns); } [HttpPost] public ActionResult Edit(News ns) { bs.Update(ns); return RedirectToAction("Index"); } //删除 public ActionResult Delete(int id) { bs.Delete(id); return RedirectToAction("Index"); } } }
Models文件下的代码文件(4个代码文件BaseOption.cs、News.cs、NewsDbContent.cs、NewsType.cs)
BaseOption.cs 这是对数据的增删改查提供的公共类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace NewsMvc.Models { public class BaseOption<T> where T : class { NewsDbContent ns_db = new NewsDbContent(); //添加 public void Add(T entity) { ns_db.Entry<T>(entity).State = EntityState.Added; ns_db.SaveChanges(); } //修改 public void Update(T entity) { ns_db.Set<T>().Attach(entity); ns_db.Entry<T>(entity).State = EntityState.Modified; ns_db.SaveChanges(); } //删除 public void Delete(params object[] keyValues) { T t = FindById(keyValues); ns_db.Set<T>().Attach(t); ns_db.Entry<T>(t).State = EntityState.Deleted; ns_db.SaveChanges(); } //查询集合 public List<T> getlist(T entity) { return ns_db.Set<T>().ToList(); } //根据Id返回查询的集合 public T FindById(params object[] keyValues) { return ns_db.Set<T>().Find(keyValues); } } }
News.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace NewsMvc.Models { public class News { [Display(Name = "编号")] public int Id { get; set; } [Required(ErrorMessage = "标题必填")] [Display(Name = "标题")] public string Title { get; set; } [Display(Name = "添加人")] public string AddUser { get; set; } [Display(Name = "内容")] public string Content { get; set; } [Display(Name = "添加时间")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] public DateTime AddDate { get; set; } [Display(Name = "备注")] public string Remark { get; set; } public string tes { get; set; } } }
NewsDbContent.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; //using System.Data.Objects.DataClasses; namespace NewsMvc.Models { public class NewsDbContent : DbContext { public DbSet<News> Newss { get; set; } public DbSet<NewsType> NewsTypes { get; set; } } }
web.config配置文件:
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=152368 --> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> </configSections> <appSettings> <add key="webpages:Version" value="1.0.0.0" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <connectionStrings> <add name="NewsDbContent" connectionString="Data Source=.;Initial Catalog=News;Integrated Security=true;" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </assemblies> </compilation> <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true" /> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> </configuration>
Sql数据库代码,数据库叫News
USE [News] GO /****** 对象: Table [dbo].[News] 脚本日期: 08/13/2015 11:09:16 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[News]( [Id] [int] IDENTITY(1,1) NOT NULL, [Title] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL, [AddUser] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL, [Content] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL, [AddDate] [datetime] NULL, CONSTRAINT [PK__News__7E6CC920] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]
最后附上程序的文件结构图
若有宝贵意见或者不清楚的请留言我们互相交流学习。
时间: 2024-11-09 03:17:13