ASP.NET Mvc4整合ExtJS4.2 MVC框架

项目结构如图所示:

ASP.NET Mvc4整合ExtJS4.2 MVC框架_第1张图片

Extjs的架构图,非常有用,可以帮助我们理解Extjs的执行流程:

ASP.NET Mvc4整合ExtJS4.2 MVC框架_第2张图片

接着是JS相关代码:

app.js

 
Ext.Loader.setConfig({ enabled: true });  //开启动态加载的依赖加载功能,默认为false不开启

Ext.application({
    name: 'Traxplorer',   //设定应用程序的命名空间(它将是controller,view.model和store的命名空间)
    path: 'app',
    autoCreateViewport: true,  //开启自动创建Viewport,它将自动去view目录下查找Viewport文件并实例化
    controllers: ['AlbumsController'],  //加载应用程序所用到的所有controller
    launch: function ()
    { 
    //Manage Application
    
    }
});
Viewport.js

 
/***
*自定义一个Viewport类继承Ext.container.Viewport
***/

Ext.define('Traxplorer.view.Viewport', {
    extend: 'Ext.container.Viewport',
    layout: 'border',
    items:
        [
            {
                region: 'center',
                flex: 1,
                title: '我的音乐专辑管理',
                xtype: 'albumlist',
                flex: 1,
                minHeight: 100
            }
        ]
});
AlbumsController.js

 

Ext.define('Traxplorer.controller.AlbumsController', {

    extend: 'Ext.app.Controller',
    stores: ['Albums'],
    models: ['Album'],
    views: ['album.List'],

    init: function () {
        this.control(
                {

                    //注意按钮内容
                    'button[text=添加]':
                    {
                        click: this.addRow
                    }

                });

    },
    addRow: function (e) {
        var store = this.getAlbumsStore();
        var isBlank = false;
 
        store.each(function (record) {
            if (null == record.data['name'] && null == record.data['artist']) {

                Ext.Msg.show(
                                {
                                    title: 'Warning',
                                    msg: 'Please update the blank album first.',
                                    buttons: Ext.Msg.OK,
                                    icon: Ext.Msg.WARNING
                                });
                 if (null == record.index)
                 record.index = 0;
                isBlank = true
                
                var grid = Ext.ComponentQuery.query('albumlist')[0];
                grid.plugins[0].startEdit(record.index, 1);
                return false; //break the loop
            }

        });
        if (!isBlank) {
 
            this.getAlbumsStore().insert(0, this.getAlbumModel().create());

        }
    }
});
model文件夹->Album.js

Ext.define('Traxplorer.model.Album', {

    extend: 'Ext.data.Model',

    fields: [

                {
                    name: 'id',
                    dataType: 'int',
                    optional: true
                },
                {
                    name: 'name',
                    dataType: 'string',
                    optional: true
                },
                {
                    name: 'artist',
                    dataType: 'string'
                }
            ],
    
    idProperty: 'id',
    
    proxy: {

        type: 'rest',
        url: '/Albums', //这里就是请求.net mvc 控制器,获取json数据
        timeout: 120000,
        noCache: false,
        
        reader:
        {
            type: 'json',
            root: 'data',
            successProperty: 'success'
        },
        
        writer:
        {
            type: 'json',
            writeAllFields: true
        },

        afterRequest: function (request, success) 
        {
            
            if (request.action == 'read') {
                this.readCallback(request);
            }
            
            else if (request.action == 'create') {
                this.createCallback(request);
            }
            
            else if (request.action == 'update') {
                this.updateCallback(request);
            }
            
            else if (request.action == 'destroy') {
                this.deleteCallback(request);
            }
        },

       
        readCallback: function (request) 
        {
            if (!request.operation.success) 
            {
                Ext.Msg.show(
                                {
                                    title: 'Warning',
                                    msg: 'Could not load Albums. Please try again.',
                                    buttons: Ext.Msg.OK,
                                    icon: Ext.Msg.WARNING
                                });
            }
        },
        
     
        createCallback: function (request) 
        {

            if (!request.operation.success) 
            {
                Ext.Msg.show(
                                {
                                    title: 'Warning',
                                    msg: 'Could not add Album. Please try again.',
                                    buttons: Ext.Msg.OK,
                                    icon: Ext.Msg.WARNING
                                });
                Ext.data.StoreManager.lookup('Albums').removeAt(0);
            }
            var grid = Ext.ComponentQuery.query('albumlist')[0];
            grid.plugins[0].startEdit(0, 1);
        },

      
        updateCallback: function (request) 
        {
            if (!request.operation.success) 
            {
                Ext.Msg.show(
                                {
                                    title: 'Warning',
                                    msg: 'Could not update Album. Please try again.',
                                    buttons: Ext.Msg.OK,
                                    icon: Ext.Msg.WARNING
                                });
            }
        },
 
        deleteCallback: function (request) 
        {
            if (!request.operation.success) 
            {
                Ext.Msg.show(
                                {
                                    title: 'Warning',
                                    msg: 'Could not delete Album. Please try again.',
                                    buttons: Ext.Msg.OK,
                                    icon: Ext.Msg.WARNING
                                });
               
                Ext.data.StoreManager.lookup('Albums').insert(0, request.operation.records[0]);
            }
        }
    }
});
store文件夹->Albums.js
Ext.define('Traxplorer.store.Albums', {
    extend: 'Ext.data.Store',
    autoLoad: true,
    autoSync: true,
    model: 'Traxplorer.model.Album'
});
view->a lbum->List.js

Ext.define('Traxplorer.view.album.List', {
    
    extend: 'Ext.grid.Panel',
    alias: 'widget.albumlist',
    store: 'Albums',
    
    dockedItems: [
        {
            xtype: 'toolbar',
            items: [
                {
                    text: '添加',
                    iconCls: 'icon-add'

                }]
        }],
    
    forceFit: true,
    columnLines: true,
    autoResizeColumns: true,
    selType: 'rowmodel',
    
    plugins: [
                Ext.create('Ext.grid.plugin.RowEditing', {
                    clicksToEdit: 2,
                    errorSummary: false

                })],
    
    initComponent: function () {
    
        this.id = "list";
    
        this.columns = [
                {
                    header: 'Album ID',
                    dataIndex: 'id',
                    sortable: false,
                    menuDisabled: true

                }, {
                    header: 'Title',
                    dataIndex: 'name',
                    editable: true,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: true
                    },

                    sortable: false,
                    menuDisabled: true

                }, {
                    header: 'Artist',
                    dataIndex: 'artist',
                    editable: true,
                    sortable: false,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: true
                    },

                    menuDisabled: true

                }, {
                    xtype: 'actioncolumn',
                    width: 16,
                    align: 'center',
                    items: [
                        {
                            icon: '../Content/images/delete.png',
                            tooltip: 'Delete',
                            handler: function (grid, rowIndex, colIndex) {
                                grid.getStore().removeAt(rowIndex);

                            } 
                        }]
                }

                ];

        this.callParent(arguments);
    }


});
Mvc4的AlbumsController代码如下:

  public class AlbumsController : Controller
    {
        AlbumRepository repoAlbum = new AlbumRepository();
        
        [HttpGet]
        [ActionName("Index")]
        public JsonResult Index(int? id)
        {

            try
            {
                if (null != id)
                {
                    Album album = repoAlbum.GetAlbum((int)id);
                    return this.Json(new { success = true, data = album }, JsonRequestBehavior.AllowGet);
                }
                var list = repoAlbum.FindAllAlbums().ToList();
                return this.Json(new { data = list }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return this.Json(new { success = false, data = "" }, JsonRequestBehavior.AllowGet);
            }


        }

        //PUT /Albums/Index/id
        [HttpPut]
        [ActionName("Index")]
        public JsonResult Update(int id, Album album)
        {

            try
            {
                Album dbAlbum = repoAlbum.GetAlbum(id);
                dbAlbum.name = album.name;
                dbAlbum.artist = album.artist;
                repoAlbum.Save();
                return this.Json(new { success = true, data = album }, JsonRequestBehavior.DenyGet);
            }
            catch
            {
                return this.Json(new { success = false, data = "" }, JsonRequestBehavior.DenyGet);
            }

        }
 
        //POST /Albums/Index/album
        [HttpPost]
        [ActionName("Index")]
        public JsonResult Create(Album album)
        {
            Response.BufferOutput = true;
            try
            {
                repoAlbum.Create(album);
                repoAlbum.Save(); 
                Response.StatusCode = 201; 
                Response.AddHeader("LOCATION", Request.Url.AbsoluteUri + "/" + album.id);
                return this.Json(new { success = true, data = album }, JsonRequestBehavior.DenyGet);

            }
            catch
            {
                return this.Json(new { success = false }, JsonRequestBehavior.DenyGet);

            }

        }
 
        //DELETE /Albums/Index/id
        [HttpDelete]
        [ActionName("Index")]
        public JsonResult Delete(int id)
        {

            try
            {

                Album album = repoAlbum.GetAlbum(id);
                repoAlbum.Delete(album);
                repoAlbum.Save();
                return this.Json(new { success = true });
            }
            catch
            {
                return this.Json(new { success = false });
            }

        }
    }
}
Index.cshtml如下:

@{
    ViewBag.Title = "我的音乐辑";
}
_Layout.cshtml代码:




    
    @ViewBag.Title
    
    
    
    
    



    @RenderBody()



项目运行结果(实现增删改查的功能)如图:

ASP.NET Mvc4整合ExtJS4.2 MVC框架_第3张图片









你可能感兴趣的:(ExtJS框架,extjs4,mvc4,c#,.NET,asp.net)