Friday, June 29, 2012

Kendo UI :Web development framework- Part 2

The MVVM model is most popular now a days . Here we will see with the sample example the use of MVVM in MVC.

To start with  MVVM  we need to first create a View Model, A view model is an observable object. This object has properties and methods. Each property will be bound to something in the HTML. In MVVM, this binding is two way, meaning that if the binding changes on the UI, the model changes, and vice versa.

Let us take a sample example where we will take display a grid and a drop down box, firstly i will create a HTML controls for grid and drop-down. And grid will be using a Template column.

 <script id="rowTemplate" type="text/x-kendo-tmpl">  
   <tr>  
     <td>${ UserName }</td>  
     <td>${ GroupName }</td>  
     <td>  
      <input type="image" id="btnremove" src="/Content/Images/DeleteIcon.gif" data-bind='events { click : removeUser }, enabled: btnSaveIsEnabled' style="width:20px;height:20px;"/></td>  
   </tr>  
 </script>  
 <div id="UserTab">  
   <div id="userGrid" data-role="grid" data-bind="source: User.UsersOf"  
     data-row-template="rowTemplate" data-columns='["User", "Group", "Remove" ]' data-pageable='{"pageSize":10}'>  
   </div>  
   <table style="width: 100; margin-top: 20px; margin-bottom: 20px">  
     <tr>  
       <td style="width: 45%">  
         <select id="dduser" data-role="dropdownlist" data-value-field="Id" data-text-field="Name"  
           data-bind="source: User.AllowableUsers, value: selectedUser, events: { change : userSelectChange }" />  
       </td>  
       <td style="width: 45%">  
         <select id="ddgroup" data-role="dropdownlist" data-value-field="Id" data-text-field="Name"  
           data-bind="source: User.AllowableGroups, value: selectedGroup, events: { change : groupSelectChange }" />  
       </td>  
       <td style="width: 10%">  
         <button id="btnSave" class="k-button" style="width: 75px" data-bind='events { click : addUser }, text: addUserText, enabled: btnSaveIsEnabled'>  
         </button>  
       </td>  
     </tr>  
   </table>  
   <a href='@Url.Action("Create", "Group", new { })' style="color: Blue; text-decoration: true;">  
     Add New Group</a><br />  
   <a href='@Url.Action("Index", "Type", new { })' style="color: Blue; text-decoration: true;">  
     Add New Type</a>  
 </div>  

Here we have created a UserViewModel that is binded to the div id :UserTab, This example also shows how to add and delete user using MVVM pattern.

 <script language="javascript" type="text/javascript">  
   $(document).ready(function () {  
     var UserViewModel = kendo.observable({  
       UserSource: new kendo.data.DataSource({  
         transport: {  
           read: {  
             url: document.URL + "/GetUser/",  
             dataType: "json",  
             type: "post",  
             complete: function (e) {  
               if (UserViewModel.UserSource == null) return;  
               UserViewModel.set("User", UserViewModel.UserSource.at(0));  
             },  
             data: { Id: 0, TypeId: 0 }  
           },  
           update: {  
             url: document.URL + "/AddUserToUser/",  
             dataType: "json",  
             type: "post",  
             complete: function (e) { }  
           },  
           parameterMap: function (options, operation) {  
             if (operation !== "read" && options.models)  
               return { models: kendo.stringify(options.models) };  
             return options;  
           }  
         },  
         schema: {  
           model: { id: "Id" }  
         }  
       }),  
       User: null,  
       selectedGroup: null,  
       selectedUser: null,  
       Id: 0,  
       TypeId: 0,  
       btnSaveIsEnabled: false,  
       addUserText: 'Add',  
       groupSelectChange: function (e) { },  
       userSelectChange: function (e) { },  
       load: function (e) {  
         this.set("Id", e.Id);  
         this.set("TypeId", e.TypeId);  
         this.UserSource.read({ Id: e.Id, TypeId: e.TypeId });  
         $("#dduser").val("").data("kendoDropDownList").text("--Choose User--");  
         $("#ddgroup").val("").data("kendoDropDownList").text("--Choose Group--");  
       },  
       addUser: function (e) {  
         if (this.get("selectedUser") == null || this.get("selectedGroup") == null) {  
           alert("Please select User and Group");  
           return;  
         }  
         if (IsUserExist(this.get("selectedUser").Id, this.get("selectedGroup").Id)) {  
           alert("User already exist");  
           return;  
         }  
         var Id = this.get("Id");  
         var TypeId = this.get("TypeId");  
         $.post("/AddUserToUser", { Id: this.get("Id"), groupId: this.get("selectedGroup").Id, userId: this.get("selectedUser").Id },  
         function (data) {  
           if (data) {  
             UserViewModel.UserSource.read({ Id: Id, TypeId: TypeId });  
             aler("User/Group Added");  
           }  
           else  
             growlSad("User not Added");  
         });  
       },  
       removeUser: function (e) {  
         if (confirm("Are you sure you want to delete this user from group?")) {  
           var Id = this.get("Id");  
           var TypeId = this.get("TypeId");  
           $.post("/DeleteUser", { UserId: e.data.UserId },  
         function (data) {  
           UserViewModel.UserSource.read({ Id: Id, TypeId: TypeId });  
         });  
         }  
       }  
     });  
     kendo.bind($("#UserTab"), UserViewModel);  
     $(document).bind(Events.OnClicked, function (event, args) {  
       UserViewModel.load({ Id: args.Selected.Id, TypeId: args.Selected.TypeId });  
       UserViewModel.set("btnSaveIsEnabled", args.Selected.IsActive);  
     });  
     $(document).bind(window.Events.OnUpdated, function (e, args) {  
       ResetFormUser();  
     });  
     function IsUserExist(userId, groupId) {  
       var gridDataSource = UserViewModel.UserSource._data[0].UsersOf;  
       for (var i = 0; i < gridDataSource.length; i++) {  
         if (userId == gridDataSource[i].UserId && groupId == gridDataSource[i].GroupId)  
           return true;  
       }  
       return false;  
     }  
     function ResetFormUser() {  
       UserViewModel.load({ Id: 0, TypeId: 0 });  
       UserViewModel.set("btnSaveIsEnabled", false);  
     }  
   });  
 </script>  

Happy Coding :) 

2 comments: