Home > DeveloperSection > Blogs > using extjs Create Login page and add,edit,update record from database.

using extjs Create Login page and add,edit,update record from database.


sencha cmd Sencha 
Ratings:
0 Comment(s)
 134  View(s)
Rate this:

first I have create a UserLogin Table

CREATE TABLE [dbo].[UserLogin](

     [UserId] [int] IDENTITY(1,1) PRIMARY KEY,

     [UserName] [varchar](100) NULL,

     [UserEmail][varchar](100) NULL,

     [PhoneNumber][varchar](100) NULL,

     [Address] [varchar](100) NULL,

     [Password] [varchar](100) NULL,

) 

Create a layout View layout.cshtml 

LAYOUT.Cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-2.2.3.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/ext-6.0.2/build/ext-all.js"></script>
<link href="~/ext-6.0.2/build/classic/theme-neptune/resources/theme-neptune-all.css" rel="stylesheet" />
    <link href="~/Content/Site.css" rel="stylesheet" />
    <script src="~/Scripts/site.js"></script>
</head>
<body>
  
<!--/.navbar -->
    <nav class="navbar navbar-inverse sidebar" role="navigation">
    <div class="container-fluid">
		<!-- Brand and toggle get grouped for better mobile display -->
		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-sidebar-navbar-collapse-1">
				<span class="sr-only">Toggle navigation</span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="#">MindStick</a>
		</div>
		<!-- Collect the nav links, forms, and other content for toggling -->
		<div class="collapse navbar-collapse" id="bs-sidebar-navbar-collapse-1">
			<ul class="nav navbar-nav">
				<li class="active"><a href="#">Home<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-home"></span></a></li>
				<li ><a href="#" id="UserProfile" class="UserProfile">Users<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-user"></span></a></li>
				 
				<li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown">Settings<span class="caret"></span><span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-cog"></span></a>
					<ul class="dropdown-menu forAnimate" role="menu">
						<li><a href="#">Action</a></li>
						<li><a href="#">Help</a></li>						 
						<li><a href="#">LogOut</a></li>
					</ul>
				</li>
			</ul>
		</div>
	</div>
</nav>
<div class="main" id="page">
@RenderBody() 

</div>
    
</body>
</html>

Create a index view  where user can login and go to Dashboard.

Index.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
      <script src="~/ext-6.0.2/build/ext-all.js"></script>
<link href="~/ext-6.0.2/build/classic/theme-neptune/resources/theme-neptune-all.css" rel="stylesheet" />
<script src="~/App/Login.js"></script>
 </head>
<body>
    <div>
        
    </div>
</body>
</html>

It is user.js file which work for user login page.

Login.js

/// <reference path="../ext-6.0.2/build/ext-all.js" />

Ext.onReady(function(){  
    var login = new Ext.FormPanel({ 
        labelWidth:100,
        url: 'api/values',     
        header : false,
        frame:false, 
        title:'Login', 
        defaultType: 'textfield',
        bodyStyle: 'background:url(images/login.png) no-repeat;  padding:20px;',
        monitorValid:true,
     
        items:[{ 
            fieldLabel:'UserID', 
            name: 'UserEmail',
            width: 400,
            fieldStyle: 'background-color: #fff; background-image: none;',
            allowBlank:false 
        },{ 
            fieldLabel:'Password', 
            name: 'Password',
            inputType: 'password',
            width:400,
            allowBlank:false 
        }],

        // All the magic happens after the user clicks the button 
        buttons:[{ 
            text:'Login',
            formBind: true, 
            // Function that fires when user clicks the button 
            handler:function(){ 
                login.getForm().submit({                  
                    method:'POST', 
                    waitTitle:'Connecting', 
                    waitMsg:'Sending data...', 
                    success: function () {                     
                        Ext.Msg.alert('Status', 'Login Successful!', function(btn, text){
                            if (btn == 'ok'){
                                var redirect = 'Home/dashboard';
                                window.location = redirect;
                            }
                        });
                    },

                    failure:function(form, action){ 
                        Ext.Msg.alert('Status', 'Login failed!'); 
                    } 
                }); 
            } 
        }] 
    });

    var win = new Ext.Window({
        title: 'Admin Login',             
        layout:'fit',
        width:450,
        height:200,
        closable: true,
        resizable: false,              
        border: false,
        buttonAlign: 'center',
        items: [login]
    });
    win.show();
});

User Login InterFace. Here user input userid and password click to login.


public bool Post(UserLogin obj)
        {
            bool success;

            var result = db.UserLogin.FirstOrDefault(x => x.UserEmail == obj.UserEmail && x.Password == obj.Password);
            if (result != null)
            {
                success = true;
              
            }
            else
            {
                 success =false;
             
            }
            return success;
        }

Login success click ok go to dashboard page.


 

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>

It is dashboard.js file which is work for  Dashboard page.

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');
});

It is user.js file use for user list where we can create, edit, update,delete record.

User.js



Ext.define('MyApp.model.User', {
    extend: 'Ext.data.Model',  
    fields: ['UserId', 'UserName', 'UserEmail', 'PhoneNumber', 'Address', 'Password'],

});


var Store=Ext.define('MyApp.store.Users', {
    extend: 'Ext.data.Store',  
    model: 'MyApp.model.User',
    proxy: {
        type: 'ajax',
        url: '/api/dashboard',        
        reader: {
            type: 'json',
            root: 'Users',
            totalProperty: 'TotalCount'
        }
    },
    remoteSort: true,
    sorters: [{
        property: 'UserName',
        direction: 'asc'
    }],
    autoLoad: { start: 0, limit: 5 },
    pageSize: 5,
});

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() {
                
            }
        });
         
        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',
						    sortable : true,
						},
						{
						    fieldLabel: 'Email',
						    sortable: false,
						    name: 'UserEmail'
						},
					    {
					        fieldLabel: 'Phone',
					        sortable: false,
					        name: 'PhoneNumber'
					    },
						{
						    fieldLabel: 'Address',
						    sortable: false,
						    name: 'Address'
						},
					    {
					        fieldLabel: 'Password',
					        name: 'Password',
					        sortable: false,
					    }
				    ]
				}
		    ],
		    buttons: [
				{
				    text: 'Save',
				    action: 'saveUser'
				}
		    ]
		}
    ]
});

Ext.define('MyApp.view.UserGrid', {
    extend: 'Ext.grid.Panel',
    xtype: 'UserGrid',
    title: 'Users',
    store: 'Users',
    multiSelect: true,
    utoScroll: true,
    listeners: {
        beforeclose: function (win) {           
        Ext.currentApp = false;
       
         
    }
    }
    ,
    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,
        displayMsg: 'Displaying {0} to {1} of {2} &nbsp;records ',
        emptyMsg: "No records to display&nbsp;"

    }],

    height:820,
    width: 400,
    closable: true,
    renderTo: Ext.getBody()

});

Ext.onReady(function () {
    Ext.get('UserProfile').on('click', function (e, t) {
         
        if (Ext.currentApp) {
            Ext.Msg.alert('Application Alert', 'window is already open !', function (btn, text) {
                if (btn == 'ok') {
                    return;
                }
            });
            return;
        }
       
        Ext.currentApp = new Ext.application({
            name: 'MyApp',
            height: 1000,
            width: '100%',
            controllers: [
                'Users'
            ],
            stores: [
                'Users'
            ],
            launch: function () {
                Ext.create('Ext.panel.Panel', {
                    layout: 'fit',
                    autoScroll: true,
                    renderTo: 'container-1010-innerCt',
                    items: [
                        {
                            xtype: 'UserGrid'
                        }
                    ]
                });
            }
            
        });
    });    
});

This is dashboard page output


This  method get userlist . and we can use paging and shorting.

public class ModelList
    {
        public IEnumerable<UserLogin> Users { get; set; }
        public int TotalCount { get; set; }
    } 
public ModelList Get(int start, int limit, string sort)
        {
            
            ModelList result = new ModelList();
            var data = db.UserLogin.AsQueryable();
            result.Users = data.OrderBy(x => x.UserName).Skip(start).Take(limit).ToList();
            result.TotalCount = data.Count();
            return result;
        } 

This is dashboard user list output.


 This is add new user form  output.


  This is edit user form Output.


This method use for add,update user.

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();
        } 
This method use for delete user.d
public void Delete(int id)
        {
            var original = db.UserLogin.Find(id);
            if (original != null)
            {
                db.UserLogin.Remove(original);
            }

            db.SaveChanges();
        }
Thanks.



Don't want to miss updates? Please click the below button!

Follow MindStick