在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
最近在学习asp.net MVC,结合前段时间学习的ExtJS,做了一个入门示例。不过还有一个json日期显示的问题没有解决。 【思路】 1.先搭建一个asp.net MVC项目。 2.将MVC项目的视图(View)部分换成ExtJS来布局。 3.连通前后台数据。 【实现效果】 【具体步骤】 参考资料(这里提供了超详细的新建一个mvc示例,亲测可建):http://www.cnblogs.com/powertoolsteam/p/aspnet-mvc5-getting-started.html 如果是跟我一样的入门级选手,建议先把上面教程完整走一遍。然后再开始这个MVC+ExtJS比较好噢。 下面我把我的步骤在这里写一下,也有对上面参考资料一些没解释超详细的比如数据库web.config里写法,一些用vs2015中文界面有不同的地方的说明。 第一步:新建一个空白mvc 至此,你已经创建了一个空白MVC项目啦。 第二步:建立项目模型M 类名:Movie.cs 【Models/Movie.cs代码] using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DemoMVC1.Models { public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } } 我们将使用 在同一文件中,添加下面的 【代码】 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DemoMVC1.Models { public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } } //MovieDBContext类代表Entity Framework的电影数据库类, //这个类负责在数据库中获取,存储,更新,处理 Movie 类的实例。 //MovieDBContext继承自Entity Framework的 DbContext基类。 public class MovieDBContext : DbContext { public DbSet<Movie> Movies { get; set; } } }
为了能够引用 using System.Data.Entity;
效果是这样的
第三步:配置你的数据库信息 找到项目的web.config文件 找到需要添加的地方 我的修改后的<connectionStrings>部分如下 完整代码如下 <?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=301880 --> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-DemoMVC-20170716025624.mdf;Initial Catalog=aspnet-DemoMVC-20170716025624;Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="MovieDBContext" connectionString="Data Source=LAPTOP-CJR9SJ22;AttachDbFilename=|DataDirectory|Movie.mdf;Initial Catalog=Movie;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <authentication mode="None" /> <compilation debug="true" targetFramework="4.5.2" /> <httpRuntime targetFramework="4.5.2" /> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> </httpModules> </system.web> <system.webServer> <modules> <remove name="FormsAuthentication" /> <remove name="ApplicationInsightsWebTracking" /> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /> </modules> <validation validateIntegratedModeConfiguration="false" /> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> </compilers> </system.codedom> </configuration> 【敲黑板、划重点:这里对于很多像我这种入门级选手就很疑惑哪里要填什么,咋配置,哪些要,哪些不要???反正我在这里弄了蛮多时间的,现在就跟各位看官仔细分析下这句增加的代码。】 ①格式:<add name ="xxxxxx" connectionString=" xxxxxxx" providerName="xxxxxxxxx" /> ②name=“xxxxx"这里,xxxxx这里的名字跟你Movie类里面的这个名字对应。 ③connectionString=" xxxxxxx"这里,是你的数据库相关信息。 Data Source=LAPTOP-CJR9SJ22;是指我的数据库服务器名称 AttachDbFilename=|DataDirectory|Movie.mdf;是指生成的我的数据库文件名字 Initial Catalog=Movie;是指数据库名称 Integrated Security=True集成验证。 如果你的数据库身份验证是sql server身份验证,应该也要写上User ID=xxxx;Pwd=xxxxx才能验证通过 ④providerName=“xxxxx"这个照写就可以了。 在进行第四步之前先对项目进行生成(选中DemoMVC1,右键选择,生成),如果运行没有错误再继续。有错误解决错误。
第四步:创建一个控制器C 选择包含视图的MVC5控制器(使用Entity Framework)
· 模型类(Model class)选择: Movie (MvcMovie.Models) . · 数据上下文类(Data context class)选择:MovieDBContext (MvcMovie.Models) 【如果这里发生错误,如图:,则取消添加,选中项目DemoMVC1,右键选择,生成。等生成成功,再重新执行第四步添加控制器操作即可。】 如果正确操作你会发现你的目录结构是这样的 至此,你的基本MVC项目算是架好了。你打开View/Movies/Index.cshtml文件,运行 然后你就可以看到你的页面了。 然后你可以添加你的电影比如: 然后你发现真的添加了: 然后你也可以试试Edit和Details以及Delete功能 现在是不是很有成就感。吼吼吼~不急,我们ExtJS还没有添加进来呢,八字还差一撇。。。。
第五步:把ExtJS包添加到项目中 具体怎么添加进来我之前的博客有讲。这里简单说一下:就是你下载好你要的版本的ExtJS包,然后选择复制,在项目里面Scripts目录下选择粘贴,即可。 弄进来以后你可能会发现看不到里面的子文件,这时,你选中”显示所有文件“,即图上三个文件图标,然后刷新一下即可。
第六步:在View/Movies/Index.cshtml文件中引入ExtJS必要文件 添加以后进行连接验证代码,保证文件加载成功 @model IEnumerable<DemoMVC1.Models.Movie> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/ExtJS6/ext-all.js"></script> <script src="~/Scripts/ExtJS6/packages/ext-locale/build/ext-locale-zh_CN.js"></script> <link href="~/Scripts/ExtJS6/classic/theme-gray/resources/theme-gray-all.css" rel="stylesheet" /> <script type="text/javascript"> //测试上面js,css文件是否连接进来用的 Ext.onReady(function () { Ext.Msg.alert("hh", "welcome"); var win = new Ext.Window({ title: "hello", width: 200, height: 300, html: '<h1>ok....just a test....</h1>' }); win.show(); }); </script> </head> <body> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th> @Html.DisplayNameFor(model => model.ReleaseDate) </th> <th> @Html.DisplayNameFor(model => model.Genre) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Html.ActionLink("Delete", "Delete", new { id=item.ID }) </td> </tr> } </table> </body> </html> 如果成功引入ExtJS,那么测试效果是这样滴~ 好的,接下来就是写入你的grid布局啦。关于grid布局,大家可以参考一下我上一篇博客,对grid布局写法有一点了解。(我也就真的只有一点了解。。。噗
第七步:在View/Movies/Index.cshtml文件中的table grid布局替换成ExtJS grid布局 @model IEnumerable<DemoMVC1.Models.Movie> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/ExtJS6/ext-all.js"></script> <script src="~/Scripts/ExtJS6/packages/ext-locale/build/ext-locale-zh_CN.js"></script> <link href="~/Scripts/ExtJS6/classic/theme-gray/resources/theme-gray-all.css" rel="stylesheet" /> @*<script type="text/javascript"> //测试上面js,css文件是否连接进来用的 Ext.onReady(function () { Ext.Msg.alert("hh", "welcome"); var win = new Ext.Window({ title: "hello", width: 200, height: 300, html: '<h1>ok....just a test....</h1>' }); win.show(); }); </script>*@ <script type="text/javascript"> Ext.onReady(function () { var movieStore = Ext.create("Ext.data.Store", { fields: [ { name: 'Title' }, { name: 'ReleaseDate' }, { name: 'Genre' }, { name: 'Price' } ], data: [ ["Test","Test","Test","Test"] ], }); Ext.create("Ext.grid.Panel", { margin: 10, width: 600, height: 400, border: true, selModel: { type:"checkboxmodel" }, store: movieStore, columns: [{ text:'@Html.DisplayNameFor(model => model.Title)', dataIndex:'Title', flex:1, align:'center' }, { text: '@Html.DisplayNameFor(model => model.ReleaseDate)', format:'Y-m-d', dataIndex:'ReleaseDate', flex:1, align: 'center', },{ text:'@Html.DisplayNameFor(model => model.Genre)', dataIndex:'Genre', flex:1, align:'center' },{ text:'@Html.DisplayNameFor(model => model.Price)', //text: 'title', dataIndex:'Price', flex:1, align:'center' }, { xtype: 'actioncolumn', text: '操作', flex: 1, align:'center', }], bbar:{ xtype:'pagingtoolbar', store:movieStore, displayInfo:true }, renderTo:Ext.getBody() }); }); </script> </head> <body> @*下面是本身自带的视图*@ @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th> @Html.DisplayNameFor(model => model.ReleaseDate) </th> <th> @Html.DisplayNameFor(model => model.Genre) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | @Html.ActionLink("Details", "Details", new { id = item.ID }) | @Html.ActionLink("Delete", "Delete", new { id = item.ID }) </td> </tr> } </table> </body> </html> 效果图: 【分析:这里,table grid显示的是数据库里面出来的数据。ExtJS grid布局里面出来的是在代码里面写死的测试布局值】
第八步:将数据库数据转换成json数据在前台ExtJS grid布局进行显示。 首先,在Controllers/MoviesController.cs文件中把数据库取出的值转化成json数据 代码 using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DemoMVC1.Models; namespace DemoMVC1.Controllers { public class MoviesController : Controller { private MovieDBContext db = new MovieDBContext(); // GET: Movies public ActionResult Index() { return View(db.Movies.ToList()); } //数据json处理 //GET: Movies/MovieData public JsonResult MoviesData() { //var moviesData = new { Title = "nie.jl", ReleaseDate = "2015-5-5", Genre= "Comedy", Price= "25" }; var moviesData = db.Movies.ToList(); return Json(moviesData, JsonRequestBehavior.AllowGet); } // GET: Movies/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // GET: Movies/Create public ActionResult Create() { return View(); } // POST: Movies/Create // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie) { if (ModelState.IsValid) { db.Movies.Add(movie); db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); } // GET: Movies/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // POST: Movies/Edit/5 // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie) { if (ModelState.IsValid) { db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); } // GET: Movies/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // POST: Movies/Delete/5 [HttpPost, ActionName("Delete |
请发表评论