第一个asp.net MVC5+ExtJS6入门案例项目

 

最近在学习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; }
        
    }
}
Movie.cs

我们将使用Movie类来表示数据库中的电影。 Movie对象的每个实例将对应数据库表的一行, Movie类的每个属性将对应表的一列。

在同一文件中,添加下面的MovieDBContext类:

【代码】

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; }
    }
}
Movie.cs

MovieDBContext类代表Entity Framework的电影数据库类,这个类负责在数据库中获取,存储,更新,处理 Movie 类的实例。MovieDBContext继承自Entity Framework的 DbContext基类。

为了能够引用DbContextDbSet,您可以在文件的顶部手动添加以下using语句,也可以对着DbContext的红色波浪线选择修补程序

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=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>
web.config

【敲黑板、划重点:这里对于很多像我这种入门级选手就很疑惑哪里要填什么,咋配置,哪些要,哪些不要???反正我在这里弄了蛮多时间的,现在就跟各位看官仔细分析下这句增加的代码。】

①格式:<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>
Index.cshtml

如果成功引入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>
Index.cshtml

效果图:

【分析:这里,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")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Movie movie = db.Movies.Find(id);
            db.Movies.Remove(movie);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
MoviesController.cs

可以在浏览器上查看

【说明:"ID":6;是因为我之前有测试过其他数据,如果你是第一条数据应该是 "ID":1;这里的ID就是你数据库里面的主键ID】

 

第九步:在View/Movies/Index.cshtml里面ExtJS里面把死的data数据换成活的json后台数据

【代码】

@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"]
                //],

                autoLoad: true,
                model: "Movie",
                proxy: {
                    type: 'ajax',                  
                    url: '/Movies/MoviesData',

                    reader: {
                        type: 'json',
                    }
                },

            });

            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>
Index.cshtml

效果

【说明:这里关于转成json以后日期的问题我一直还没解决,如果有大神看到可以指点的话最好了。。我也有百度一些方法,但没什么效果。。。】

 

第十步:把Edit、Details、Delete添加到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"]
                //],

                autoLoad: true,
                model: "Movie",
                proxy: {
                    type: 'ajax',                  
                    url: '/Movies/MoviesData',

                    reader: {
                        type: 'json',
                    }
                },

            });

            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',
                    items: [{
                        icon: '../Content/images/user_edit.png',
                        tooltip: 'Edit',
                        handler: function (grid, rowIndex, colIndex) {
                            var data = grid.getStore().getAt(rowIndex);
                            //Ext.MessageBox.alert('Edit', data.get('Title'));
                            //Ext.MessageBox.alert('Edit', rowIndex);
                            document.location.href = 'Movies/Edit/' + (rowIndex + 1) //跳转到处理页                       

                        }
                    }, {
                        icon: '../Content/images/user_data.gif',
                        tooltip: 'Detail',
                        handler: function (grid, rowIndex, colIndex) {
                            document.location.href = 'Movies/Details/' + (rowIndex + 1)

                        }
                    }, {
                        icon: '../Content/images/user_delete.png',
                        tooltip: 'Delete',
                        handler: function (grid, rowIndex, colIndex) {
                            document.location.href = 'Movies/Delete/' + (rowIndex + 1)

                        }
                    }]
               
                }],
                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>
Index.cshtml

显示效果

【说明:如果你也想要小人图标,那么你只能自己去找,然后添加到项目的Content文件夹,新建一个images文件夹,把图片装进去】

在此,基本一个MVC+ExtJS6的一个小项目就构建出来了。

第一次写这种从头到尾的文章,可能有些地方还是不够教程细致的,比如仔细的看官就会发现我的项目名字可能会在DemoMVC和DemoMVC1之间切换,其实是因为我自己做的时候用的DemoMVC项目名,因为写博客要重弄,所以只能取个DemoMVC1的项目名字。所以!!!各位看官不要直接复制我贴的整个源码到你的代码里哦,按照步骤来添加自己需要的部分才是最好的,遇到问题多去查,慢慢就学到很多了。

 

【资料分享】

1.一些关于json数据格式的整理:http://www.cnblogs.com/SkySoot/archive/2012/04/17/2453010.html

2.处理json输出日期问题(虽然我没有解决,,不过或许有用):http://www.cnblogs.com/yhql/archive/2012/02/23/2365098.html

3.如何将Controller中的数据处理成json数据并传到前台:http://www.phpstudy.net/b.php/71230.html

 

转载于:https://www.cnblogs.com/GuliGugaLiz/p/7218288.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值