HOW TO USE CRUD OPERATION IN MVC USING EXTJS

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
JQuery  Mvc  Sencha 
 587  View(s)
Ratings:
Rate this:
we want to add, update, delete data in mvc using extjs. please help me how will do this.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: How to use crud operation in mvc Using ExtJs

    we are going to complete curd opration using extjs. follow step by step.
    Users.js
    Ext.define('MyApp.model.User', {
        extend: 'Ext.data.Model',  
        fields: ['UserId','UserName', 'UserEmail', 'PhoneNumber', 'Address', 'Password']    
    });
    
    Ext.define('MyApp.store.Users', {
        extend: 'Ext.data.Store',  
        model: 'MyApp.model.User',
        proxy: {
            type: 'ajax',
            url: '/api/dashboard',
            reader: {
                type: 'json'
            }
        },
        autoLoad: true
    });
    
    Ext.define('MyApp.controller.Users', {
        extend: 'Ext.app.Controller',
        refs: [
            {
                ref: 'UserGrid',
                selector: 'UserGrid'
            },
            {
                ref: 'DelUserBtn',
                selector: 'UserGrid button[action=deleteUser]'
            }
    
        ],
    
        init: function () {
            this.control({
                'UserGrid': {
                    itemdblclick: this.onUserGridItemDblClick,
                    selectionchange: this.onUserGridSelectionChange
                },
                'UserGrid button[action=addUser]': {
                    click: this.onAddUserClick
                },
                'UserGrid button[action=deleteUser]': {
                    click: this.onDelUserClick
                },
                'UserForm button[action=saveUser]': {
                    click: this.onSaveUserClick
                }
            });
        },
        onDelUserClick: function (button) {
            var grid = button.up('grid'),
        		selection = grid.getSelectionModel().getSelection();         
            Ext.Array.each(selection, function (model, index) {
                Ext.Ajax.request({
                    url: '/api/dashboard/'+ model.data.UserId,
                    method: 'DELETE',               
                    success: function () {
                        model.destroy();
                    },
                    failure: function () {
    
                    }
                });
            });    
            grid.store.load();
        },
    
        onUserGridSelectionChange: function (grid, selected) {
            this.getDelUserBtn().setDisabled(selected.length === 0);
        },
    
        onUserGridItemDblClick: function (grid, record, item) {
            this.showUserForm(record);
        },
    
        onAddUserClick: function () {
            var newUser = Ext.create(MyApp.model.User);
    
            this.showUserForm(newUser);
        },
    
        showUserForm: function (model) {       
            var userWin = Ext.create('MyApp.view.UserForm'),
        		form = userWin.down('form');
    
            form.loadRecord(model);
            userWin.show();
        },
    
        onSaveUserClick: function (button) {
            var self = this;
            var form = button.up('form'),
        		win = form.up('window'),
        		data = form.getValues(),
        		user = form.getRecord();
            Ext.Ajax.request({
                url: '/api/dashboard',
                method: 'POST',            
                jsonData:form.getValues(),
                success: function () {              
                    self.getUserGrid().store.load();               
                },
                failure: function() {
                    
                }
            });
            //user.set(data);
            //user.save();
            // this.getUserGrid().store.load();
           
            win.destroy();
        }
    });
    
    Ext.define('MyApp.view.UserForm', {
        extend: 'Ext.window.Window',
        xtype: 'UserForm',
        modal: true,
        layout: 'fit',
        height: 300,
        width: 400,
        title: 'UserForm',
        items: [
    		{
    		    xtype: 'form',
    		    bodyPadding: 5,
    		    items: [
    				{
    				    xtype: 'fieldset',
    				    title: 'User Info',
    				    defaults: {
    				        xtype: 'textfield',
    				        labelWidth: 100,
    				        width: 300
    				    },
    				    items: [
                            { 
                                name: 'UserId',
                                hidden: true
                            },
    						{
    						    fieldLabel: 'Name',
    						    name: 'UserName'
    						},
    						{
    						    fieldLabel: 'Email',
    						    name: 'UserEmail'
    						},
    					    {
    					        fieldLabel: 'Phone',
    					        name: 'PhoneNumber'
    					    },
    						{
    						    fieldLabel: 'Address',
    						    name: 'Address'
    						},
    					    {
    					        fieldLabel: 'Password',
    					        name: 'Password'
    					    }
    				    ]
    				}
    		    ],
    		    buttons: [
    				{
    				    text: 'Save',
    				    action: 'saveUser'
    				}
    		    ]
    		}
        ]
    });
    
    Ext.define('MyApp.view.UserGrid', {
        extend: 'Ext.grid.Panel',
        xtype: 'UserGrid',
        title: 'Users',
        store: 'Users',
        multiSelect: true,
        columns: [
            { text: 'Name', dataIndex: 'UserName', flex: 1 },
            { text: 'Email', dataIndex: 'UserEmail', flex: 1 },
            { text: 'Phone', dataIndex: 'PhoneNumber', flex: 1 },
               { text: 'Address', dataIndex: 'Address', flex: 1 },
                  { text: 'Password', dataIndex: 'Password', flex: 1 }
        ],
        tbar: [
    		{
    		    text: 'Add',
    		    iconCls: 'add',
    		    action: 'addUser'
    		},
    		{
    		    text: 'Delete',
    		    iconCls: 'delete',
    		    action: 'deleteUser',
    		    disabled: true
    		}
        ],
        bbar: [{
            xtype: 'pagingtoolbar',
            store: 'Users',
            displayInfo: true
        }],
        height:'auto',
        width: 400,
        renderTo: Ext.getBody()
    });
    
    Ext.onReady(function () {
        Ext.get('UserProfile').on('click', function (e, t) {
            if (MyApp.alreadyInitiated) {
                return;
            }
            Ext.application({
                name: 'MyApp',
                height: 900,
                width: '100%',
                controllers: [
                    'Users'
                ],
                stores: [
                    'Users'
                ],
                launch: function () {
                    Ext.create('Ext.panel.Panel', {
                        layout: 'fit',
                        renderTo: 'container-1010-innerCt',
                        items: [
                            {
                                xtype: 'UserGrid'
                            }
                        ]
                    });
                }
            });
        });    
    });
    dashboard.js
    
    Ext.define('PagePanel', {
        extend: 'Ext.panel.Panel',
        height: '100%',  
        renderTo: Ext.getBody(),
        title: 'Dashboard',
        layout: {
            type: 'table',
            columns: 1,
            tableAttrs: {
                style: {
                    width: '100%', height: '100%'
                }
            },
            tdAttrs: {
                style: { border: '1px solid black' }
            }
        },
        listeners : {
            afterrender : function(panel) {
                var header = panel.header;
                header.setHeight(51);
            }
        },
    
        initComponent: function () {
            this.callParent(arguments);       
                this.add({
                    xtype: 'container',
                    style: { height: '100%' }
                });
           
        }
    });
    
    Ext.onReady(function () {
        Ext.create('PagePanel');
    });
    dashboard.cshtml
    @{
        ViewBag.Title = "dashboard";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    <script src="~/App/dashboard.js"></script>
    <script src="~/App/Users.js"></script>
    <style>
    .add{
      background: url('http://www.famfamfam.com/lab/icons/silk/icons/add.png') no-repeat; 
    }
    .delete{
      background: url('http://www.famfamfam.com/lab/icons/silk/icons/delete.png') no-repeat; 
    }
    </style>
    Api
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace SenchaApi.Controllers
    {
        public class DashboardController : ApiController
        {
            forumEntities db = new forumEntities();
            // GET api/dashboard
            public IEnumerable<UserLogin> Get()
            {
                var result=db.UserLogin.ToList();
                return result;
            }
    
            // GET api/dashboard/5
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/dashboard
            public void Post(UserLogin obj)
            {
                var original = db.UserLogin.Find(obj.UserId);
                if (original != null)
                {
                    original.UserName = obj.UserName;
                    original.UserEmail = obj.UserEmail;
                    original.PhoneNumber = obj.PhoneNumber;
                    original.Password = obj.Password;
                    original.Address = obj.Address;
                } 
                else
                {
                    db.UserLogin.Add(obj);
                }
    
                db.SaveChanges();
            }
    
            // PUT api/dashboard/5
            public void Put(int id, [FromBody]string value)
            {
            }
    
            // DELETE api/dashboard/5
            public void Delete(int id)
            {
                var original = db.UserLogin.Find(id);
                if (original != null)
                {
                    db.UserLogin.Remove(original); 
                }            
    
                db.SaveChanges();
            }
        }
    }
    
    DataBase UserLogin Table
          Create Table [UserLogin]
    	 (
    	  [UserId] int primary key identity(1,1),  
              [UserName] varchar(100), 
              [UserEmail] varchar(100), 
              [PhoneNumber] varchar(100), 
              [Address] varchar(100), 
              [Password] varchar(100) 
    	 )
    OutPut


    I hope it will helpful for you.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!