Saturday, September 6, 2014

Magento Soap API call in Asp.net C#: Save Order

Click here to follow the steps to add the Magento reference to your asp.net C# application . I think, doing a order through Magento Api is a tricky  process. You need to follow the perfect flow to make an order into Magento store. For placing an order, you should have a Magento Store_ID, Api_USER_Name, Api_User_Key. Get your SessionId(32-bit string) by using Api_USER_Name and Api_User_key. Beacause, you have to use the SessionId in every api call.
First, you have to create the Shopping cart Id. If Cart Id is generated successfull, then you have to  add the Customer Info, Customer Address, Product, Shipping type and Payment type respectively. You should add the all details in the right flow then only order will be saved successfully. Follow the below code.


protected void SaveOrder()
{
string storeId = "YOUR_Store_Id"; 
               
string mlogin=null;                 
try
{
    mlogin = mservice.login("YOUR_API_UserName", "YOUR_API_UserKey");
   //Here mlogin means SessionID. We have to use it in every call.                    
 }
 catch (Exception ex)
 {
    // Handle the error if service is not availiable
   //Magento Save Order- Service login failed with response 
 }

                   

 int Shopping_Cart_ID = 0;
 try
   {
    // Creating Shopping CartID. Without CradID, you can't proceed next step.
    Shopping_Cart_ID = mservice.shoppingCartCreate(mlogin, storeId);

   }
 catch
   {
     // Handle the error if Shopping cart id not created   }

 if (Shopping_Cart_ID != 0) // Open if Shopping CartID is created
   {
     try
        {
          shoppingCartCustomerEntity customer = new shoppingCartCustomerEntity();
       //If you have customer ID then do the below method. Otherwise go for guest.
          if (Session["Customer_ID"].ToString() != null)
             {
                            
              customerCustomerEntity customerCustomerEntity = mservice.customerCustomerInfo(mlogin, int.Parse(Session["Customer_ID"].ToString()), null);
              customer.mode = "customer";
              customer.customer_id = customerCustomerEntity.customer_id;
              customer.customer_idSpecified = true;
              customer.email = customerCustomerEntity.email;
              customer.password = customerCustomerEntity.password_hash;
              customer.confirmation = customerCustomerEntity.confirmation.ToString();
              customer.website_id = customerCustomerEntity.website_id;
              customer.website_idSpecified = true;
              customer.store_id = customerCustomerEntity.store_id;
              customer.store_idSpecified = true;
              customer.group_id = customerCustomerEntity.group_id;
              customer.group_idSpecified = true;
                            
             }
         else
             {
              customer.mode = "guest";
              customer.firstname = "Teja";
              customer.lastname = "Prakash";
              customer.email = "Info@tejaprakash.com";
              customer.website_id = 0;
              customer.website_idSpecified = true;

             }
                        
        bool result = false;
      //If call success then your result will be 'TRUE'. Otherwise 'False'.
     //Saving Customer Info to Cart
        result = mservice.shoppingCartCustomerSet(mlogin, Shopping_Cart_ID, customer, storeId);
                            

       //Setting Customer address to Shopping Cart
       List<shoppingCartCustomerAddressEntity> customer_Address_List = new List<shoppingCartCustomerAddressEntity>();
       shoppingCartCustomerAddressEntity customer_Address_Shipping = new shoppingCartCustomerAddressEntity();

       //You have to set the both shipping and billing address of Customer.  
      // If you have already Magento User address list then use below field "address_id". 
     // customer_Address_Shipping.address_id = Session["Customer_Address_ID"].ToString();
        customer_Address_Shipping.mode = "shipping";
        customer_Address_Shipping.firstname = "Teja";
        customer_Address_Shipping.lastname = "Prakash";
        customer_Address_Shipping.company = "";
        customer_Address_Shipping.street = "Road no.6,Madhapur";
        customer_Address_Shipping.city = "Hyderabad";
        customer_Address_Shipping.country_id = "IN";
        customer_Address_Shipping.region = "Hyderabad";
        customer_Address_Shipping.telephone = "123456789";
        customer_Address_Shipping.fax = "";
        customer_Address_Shipping.postcode = "500081";
                             
     // Below 4 fileds are used to set their Shipping address as default shipping, billing. If necessary. 
          // customer_Address_Shipping.is_default_shipping = 1;
         // customer_Address_Shipping.is_default_shippingSpecified = true;
        // customer_Address_Shipping.is_default_billing = 1;
       // customer_Address_Shipping.is_default_billingSpecified = true;
                          
     //Adding shipping address to list.
        customer_Address_List.Add(customer_Address_Shipping);
                           
    //Set Billing address now as like shipping.
                            
      shoppingCartCustomerAddressEntity customer_Address_Billing = new shoppingCartCustomerAddressEntity();
      customer_Address_Billing.mode = "billing";
     // If you have already a Magento User address list then use below field "address_id".
      //customer_Address_Billing.address_id = Session["Customer_Address_ID"].ToString();
       customer_Address_Billing.firstname = "Teja";
       customer_Address_Billing.lastname = "Prakash";
       customer_Address_Billing.company = "";
       customer_Address_Billing.street = "Road No.6, Madhapur";
       customer_Address_Billing.city = "Hyderabad";
       customer_Address_Billing.country_id = "IN";
       customer_Address_Billing.region = "Hyderabad";
       customer_Address_Billing.postcode = "500081";
       customer_Address_Billing.telephone = "";
       customer_Address_Billing.fax = "";

      // Below 4 fileds are used to set their Shipping address as default shipping, billing. If necessary. 
         // customer_Address_Billing.is_default_shipping = 1;
        // customer_Address_Billing.is_default_shippingSpecified = true;
       // customer_Address_Billing.is_default_billing = 1;
      // customer_Address_Billing.is_default_billingSpecified = true;

     //Adding billing address to the list.
       customer_Address_List.Add(customer_Address_Billing);


     //Saving Customer Address to the cart.
      result = mservice.shoppingCartCustomerAddresses(mlogin, Shopping_Cart_ID, customer_Address_List.ToArray(), null);
                           
                           

     //Add Product Information.
     List<shoppingCartProductEntity> Products_list = new List<shoppingCartProductEntity>();
     shoppingCartProductEntity Product = new shoppingCartProductEntity();
                            
     //Give your Magento Product ID. Product must be in active state.
     Product.product_id = 2; 
     Products_list.Add(Product);
    //Saving the Product.
     result = mservice.shoppingCartProductAdd(mlogin, Shopping_Cart_ID, Products_list.ToArray(), null);
                                   

     // Set your Shiping type method. Magento provides so many shipping service for you like Fedex, Ups, USPS,..etc.
      // If you need list of codes then go for 'shoppingCartShippingList' method. 
      //For Flatrate - 'flatrate_flatrate',
      //FedEx Standard Overnight - 'fedex_STANDARD_OVERNIGHT'
     //UPS - UPS Second Day Air - 'ups_2DA'...etc
      result = mservice.shoppingCartShippingMethod(mlogin, Shopping_Cart_ID, "flatrate_flatrate", storeId);
                                  

     // Add Payment method to cart.
      shoppingCartPaymentMethodEntity payment_method_entity = new shoppingCartPaymentMethodEntity();
                                    
       bool creditCardPayment = false;
       // For Non-Credit card payments use below condition. 
          if (!creditCardPayment)
             {
               payment_method_entity.method = "checkmo";
               payment_method_entity.cc_cid = null;
               payment_method_entity.cc_owner = null;
               payment_method_entity.cc_number = null;
               payment_method_entity.cc_type = null;
               payment_method_entity.cc_exp_month = null;
               payment_method_entity.cc_exp_year = null;
             }
      //For credit card Payment, you have to mention the card type. Few methods are below.
      //Or call 'shoppingCartPaymentList' to get the list of payments.
     //Sample call for Payments list method like...shoppingCartPaymentMethodResponseEntity[] list = mservice.shoppingCartPaymentList(mlogin, Shopping_Cart_ID, null);

          else
              {
                string cardtype = Session["CardType"].ToString();
                if (string.Equals(cardtype, "Visa", StringComparison.OrdinalIgnoreCase))
                    {
                      cardtype = "VI";
                    }
               else if (string.Equals(cardtype, "MasterCard", StringComparison.OrdinalIgnoreCase))
                    {
                      cardtype = "MC";
                    }
               else if (string.Equals(cardtype, "American Express", StringComparison.OrdinalIgnoreCase))
                    {
                      cardtype = "AE";
                    }
               else if (string.Equals(cardtype, "Discover", StringComparison.OrdinalIgnoreCase))
                    {
                      cardtype = "DI";
                    }
                else
                    {
                      cardtype = "OT";
                    }
                                                                               

               payment_method_entity.po_number = "OrderNumber"; //OD123456
               payment_method_entity.method = "ccsave";  //Fixed
               payment_method_entity.cc_cid = null;  //optional
               payment_method_entity.cc_owner = "Name";  //Ex: Teja Prakash
               payment_method_entity.cc_number = "CreditCardNumber";  //Ex: 4111111111111111
               payment_method_entity.cc_type = cardtype;    //Ex: VI for VISA        
               payment_method_entity.cc_exp_month = "CreditExpirationMonth"; //Ex: 09
               payment_method_entity.cc_exp_year = "CreditExpirationYear";   //Ex: 2018

              }
        //Saving Payment method details.
          result = mservice.shoppingCartPaymentMethod(mlogin, Shopping_Cart_ID, payment_method_entity, null);

        //If you added all the details to cart successfully then only you need to make an order otherwise it fails.
           if (result)
              {
                 string order_ID = string.Empty;
                 order_ID = mservice.shoppingCartOrder(mlogin, Shopping_Cart_ID, storeId, null);
                                                  
           //On successfull order, you will get the ORDERID from Magento.
                 if (order_ID != string.Empty)
                       {
                           return order_ID;
                        }

                }

   }
catch(Exception ex)
    {
     // Handle  your Error      }

  }// Close Shopping CartID

  return 0;
}

After successful order, you will get the Order Id otherwise zero. Product quantity will be decreased automatically after the order.




Read More »

Saturday, August 23, 2014

Magento Soap API call in Asp.net C#: Customer Module

The Customer module allows you to create, update, delete and retrieve customers and customer addresses. Click here to know more about Customer module.After the SOAP service added successfully to your project then get the reference of it in your class.

Add the namespace:

using MagentoRestApi.com.tejaprakash;

Here, com.tejaprakash is a service name which is given while creating web service. And add service reference like below.

MagentoService mservice = new MagentoService();

Before calling/consuming any Magento service module, you should call Magento service login with the details ApiUserName and ApiUserKey. On success,  you will get 32 bit string(SessionId) like 9b0f014c36868XXXX7dff1fe43fff1d. We have to use this in every call.

 var mlogin = mservice.login("YOURApiUserName", "YOURApiUserKey");

Create new Customer:

For creating/registering new customer using Magento api in C# is very first step in Customer Module. After creating customers, you can able to get the list of customers or customer details.
First, you need to create customer. If it successful then you will get back 'Customer Created ID'. Then you have to add address for the customer. Follow the below code to create new customer through Magento SOAP Api in C#.

      try
            {

            int newCustomerCreateID = 0;
            int createAddressID = 0;
            filters myfilter = new filters();
         
            // Create Customer
            customerCustomerEntityToCreate customerCreate = new customerCustomerEntityToCreate();
         
            //fill attributes
            customerCreate.email = "info@tejaprakash.com";
            customerCreate.password = "123456";
            customerCreate.firstname = "Teja";
            customerCreate.lastname = "Prakash";
            customerCreate.middlename = "";
            customerCreate.store_id = 1;
            customerCreate.store_idSpecified = true;
            customerCreate.website_id = 1;
            customerCreate.website_idSpecified = true;
            customerCreate.group_id = 1;
            customerCreate.group_idSpecified = true;
            customerCreate.suffix = "P";
            customerCreate.prefix = "Mr.";
            customerCreate.dob = "01/02/0101; //"DD/MM/YYYY";
            customerCreate.taxvat = "123456";
            customerCreate.gender = 1; //1-Male;2-Female
            customerCreate.genderSpecified = true;

      //Here, mlogin will be your Service token and Customer entity.
     newCustomerCreateID = mservice.customerCustomerCreate(mlogin, customerCreate);

         
            // If Customer added successfully then you will get back with value otherwise response will be zero.
            // Add Address
            if (newCustomerCreateID != 0)
            {
                customerAddressEntityCreate customerAddress = new customerAddressEntityCreate();

                customerAddress.city = "Hyderabad";
                customerAddress.company = "Prakash Blog";
                customerAddress.region_id = 2;   //CountryID
                customerAddress.region_idSpecified = true;
                customerAddress.country_id = "IN";

                string[] streettxt = { "123,Madhapur" };
                customerAddress.street = streettxt;

                customerAddress.fax = "986754321";
                customerAddress.firstname = "Teja";
                customerAddress.lastname = "Prakash";
                customerAddress.middlename = "";
                customerAddress.postcode = "500081";
                customerAddress.prefix = "Mr.";
                customerAddress.suffix = "P";
                customerAddress.telephone = "123456789";
                
               //If you specify 'true' for is_default_billing and is_default_shipping. Then this address will be your default shipping and billing. Otherwise none. 
                customerAddress.is_default_billing = true;
                customerAddress.is_default_shipping = true;
             

             
               createAddressID = mservice.customerAddressCreate(mlogin, newCustomerCreateID , customerAddress);
             
//If Customer Address added successfully then you will get back with value otherwise response will be zero.
                if (createAddressID != 0)
                {

                    Session["Customer_ID"] = newCustomerCreateID ;

                    Session["Customer_Address_ID"] = createAddressID;

                    mservice.endSession(mlogin);
                 

                }
                else
                {
                    mservice.customerCustomerDelete(mlogin, newCustomerCreateID );
                 
                    //lbl_MsgResult.Text = "Sorry, there was a problem saving your address information.";

                    mservice.endSession(mlogin);
                 
                }
            }

            else
            {
             
                //lbl_MsgResult.Text = "Sorry, there was a problem saving your information.";
             
                mservice.endSession(mlogin);
             
            }

            }
     catch (Exception ex)
            {
                //Unable to create account
            }

Retrieve customer:

Retrieve the customer details by using methods CustomerInfo and CustomerList. CustomerInfo method will provide you only single customer details. If you want list of customers then you use CustomerList method. Follow the below code to get the customer details.


filters myfilter = new filters();
customerCustomerEntity[] customers = mservice.customerCustomerList(mlogin, myfilter);

if (customers.Length > 0)
                {
               
                    foreach (var cust in customers)
                    {
                         var id = cust.customer_id;
                         string name = custome.firstname;
                         string pwdhash = cust.password_hash;
                    }
               }

Delete customer:

To delete the customer record, use CustomerDelete method. You should need SessionId and Customer created Id.

mservice.customerCustomerDelete(mlogin, newCustomerCreateID );

Customer Sign-in:

Magento doesn't providing you sign-in Api by default. If your are PHP developer then you can write your own Api call. But it was question for non-PHP's. I tried it using Customer Module Api's and with a small logic. It worked like a charm.
When customer use to login with their Username/Email and password. By using Email and Password, we need to validate it.
In Magento, CustomerInfo method provides you all the details regarding customer including password. But password is encrypted in a format HASH: SALT (3264b70e91268d8ecf59fffd47db675c:KSC2VzugdDdUbghTHoTouZeMLxk14TYU).  We have to separate and decrypt it. And match it with the customer password(typed). Matches, signed otherwise failed.


 protected void Magento_login()
        {
            try
            {
                mservice.Url = "";
             
                mlogin = mservice.login("ApiUserName", "ApiUserKey");
             
                filters filter = new filters();
                complexFilter[] cmxFilter = new complexFilter[1];
                complexFilter mcmxFilter = new complexFilter();
                mcmxFilter.key = "email";
                associativeEntity entity = new associativeEntity();
                entity.key = "in";
                entity.value = "info@tejaprakashp.com";
                mcmxFilter.value = entity;
                cmxFilter[0] = mcmxFilter;
                filter.complex_filter = cmxFilter;
                var filters = new filters();
                filters.complex_filter = cmxFilter;
                customerCustomerEntity[] customers = mservice.customerCustomerList(mlogin, filters);
             
                if (customers.Length > 0)
                {
                    //var data = mservice.customerCustomerList(mlogin);
                    foreach (var custome in customers)
                    {
                        var id = custome.customer_id;
                        string pwdhash = custome.password_hash;
                        var password = "12345678";
                        MD5 md5Hash = MD5.Create();
                        string[] hashh = pwdhash.Split(':');
                        string randomhash = hashh[1].ToString();
                        string bytehash = hashh[0].ToString();
                        string hash = GetMd5Hash(md5Hash, password, randomhash);

                        bool signed = VerifyMd5Hash(bytehash, hash);
                        if (signed)
                        {
                            //Do something after succesful login.

                            customerAddressEntityItem[] customers_address = mservice.customerAddressList(mlogin, id);
                         
                            customerAddressEntityItem shipping = new customerAddressEntityItem();

                            shipping = customers_address[0];

                        }
                        else
                        {
                            mservice.endSession(mlogin);
                            //Invalid Password
                      
                        }
                    }

                }
                else
                {
                    mservice.endSession(mlogin);
                    //Invalid UserName
                 
                }
            }
            catch(Exception ex)
            {
             
                // Do Something
            }
        }

     

 public static string GetMd5Hash(MD5 md5Hash, string input, string random)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(random + input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }


 public static bool VerifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            //string hashOfInput = GetMd5Hash(md5Hash, input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(input, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
     
Read More »

Saturday, August 9, 2014

Magento API soap call in C#: Integration

     I came up with a new task i.e Magento API SOAP calling in asp.net C# application. This platform is mostly used by the PHP developers. Interestingly, i got this task in the Dot net side. Magento basic topics looks like simple and easy to do but when we are going to the topic deeper and deeper then everything  will looks like a tough and tight. Required PHP framework installed server to install Magento platform i.e another part of work to install Magento into your server. To know more about Magento installation(click here) and Soap API(click here). 
    After successful Magento installation, you will be provided with your API details like serviceURL, ApiUserName, ApiUserKey and store details. I have used V2 SOAP version here.

Adding a Web Reference:

 First, create a new Asp.net C# web application. Then right click on the project and select 'Add service Reference'.






After selecting 'Add Service Reference'. You will get a new window called 'Add Service Reference'. Click on 'Advanced' button.



Then, you will another window called 'Service Reference Settings'. Click on 'Add Web Reference' button.


Give your Magento hosted URL.Then click on 'Go' button to get the Magento Service.
There are two SOAP version in Magento. I have used version 2 here.
EX:
SOAP v1 url: http://Hostname/api/soap/?wsdl=1
SOAP v2 url: http://Hostname/api/v2_soap/?wsdl=1


If URL access then you will get the service list as like below. And then click on 'Add Reference' button to complete the process.



On successful, you will get the reference in your project as like below.



CLICK HERE FOR ADD NEW CUSTOMER THROUGH MAGENTO SOAP API.
CLICK HERE FOR PLACE ORDER THROUGH MAGENTO SOAP API.

Have a nice day!!!





      
Read More »

Saturday, July 5, 2014

Working with Knockoutjs in MVC C# - Create, delete and update the data.

        You need some Knockoutjs basics to understand this article. I have already posted the Knockoutjs basics. And this tutorial explains you about the create, delete and update the grid data in KnockoutJs with MVC. Firstly, create your new MVC project with Web Api.

Watch sample output video:

video



Wep Api:

       After creating Entity data model, repositories in the project then you need to create a new Api Controller called "UserApiController". By default, you will get Get, Post, Put and Delete http methods. Follow the methods code below.

Get:
      It is used to get the list of records/single record. It is used only to retrieve the data. Follow the Get Method below. First one is to get all the list. Another to get the specific user information.
       
     // GET api for User list.
        [Route("v1/GetUsers")]
    public IQueryable<User> GetUsers()
    {
      return db.Users;
    }

       // GET api for particular User
        [Route("v1/GetUser/{id}")]
    [ResponseType(typeof(User))]
     public IHttpActionResult GetUser(long id)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return NotFound();
            }

            return Ok(user);
        }


Post:
    It is used to create new record. It have no restrictions on data length. Follow the POST method below. You have to post along with user entity model.

       // POST api/User
    [Route("v1/PostUser")]
    [ResponseType(typeof(User))]
     public IHttpActionResult PostUser(User user)
      {
        if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

      db.Users.Add(user);
      db.SaveChanges();
      return StatusCode(HttpStatusCode.NoContent);
       }

Delete:
It used to delete the records in the database.

      // DELETE api/User/5
    [Route("v1/DeleteUser/{id}")]
    [ResponseType(typeof(User))]
     public IHttpActionResult DeleteUser(long id)
       {
         User user = db.Users.Find(id);
         if (user == null)
          {
            return NotFound();
           }

       db.Users.Remove(user);
       db.SaveChanges();

       return Ok(user);
       }

Put:
It mainly used to update the data or records in the server. Following code will update the user details in the server if user exists.

        // PUT api/User/5
    [Route("v1/PutUser}")]
     public IHttpActionResult PutUser( User user)
     {
        
         db.Entry(user).State = EntityState.Modified;
         db.SaveChanges();
        
        return StatusCode(HttpStatusCode.NoContent);
      }

ViewModel:

        It is a pure-code representation of data and operations on a UI. It doesn't have any concept of buttons and styles. It is pure JavaScript object.
Then create a new JavaScript file as "UserViewModel" or place the script in the VIEW. Follow the code below.

$(document).ready(function () {
 //Create new function called 'userViewmodel'.
    function userViewmodel() {

//Converting 'this' into another variable (traditionally called 'self').It can be used throughout the ViewModel. Because 'self is' captured in the function closure, it remains available and consistent in any nested functions, such as KO.
 
 
        var self = this;
     //Declaring all required attributes...
 
        self.UserId = ko.observable("");
        self.FullName = ko.observable("");
        self.FirstName = ko.observable("");
        self.LastName = ko.observable("");
        self.Email = ko.observable("");
        self.Phone = ko.observable("");
        self.Address = ko.observable("");
        self.City = ko.observable("");
        self.State = ko.observable("");
        self.Gender = ko.observable("");
        self.UserGroup = ko.observable("");
        self.Status = ko.observable(true);
       
     //Creating an array object.

        var user = {
            UserId: self.UserId,
            FullName: self.FullName,
            FirstName: self.FirstName,
            LastName: self.LastName,
            Email: self.Email,
            Address: self.Address,
            City: self.City,
            State: self.State,
            Phone: self.Phone,
            Gender: self.Gender,
            Status: self.Status,
            UserGroup: self.UserGroup

        }
     
        self.user = ko.observable();
        self.users = ko.observableArray(); 
       
        //Enabling 'Add New User' button by default.
          self.CreateNewUserButton = ko.observable(true);
        //Disabling 'Create new user' Div by default.
          self.NewUserDiv = ko.observable(false);
        //Disabling 'Edit user' Div.
          self.EditUserDiv = ko.observable(false);
        //Enabling Edit Button.
          self.EditButton = ko.observable(true);

//////Getting users list///////

      //Calling 'getUsersList' function on document load.
        getUsersList();
     
        function getUsersList() {
            $.getJSON("/v1/GetUsers")
            .done(function (data) {
              //Applying JSON data to KO array.
                self.users(data);
            });
        }

//////Add new user////////
 
     //Add new Button function       
        self.CreateUserbtn = function () {
            self.CreateNewUserButton(false);//Disabling 'Add User User' button.
            self.NewUserDiv(true);         //Enabling NewUser Div here.
            self.user(null);              //Making 'user' array object to null. 
        }
        
     //Create new user ajax post function.
        self.createUser = function () {
            if (user.FullName().trim() == "" ) {
                    toastr.error('Please enter Name!', '')
                    return false;
                }
                  $.ajax({
                    url: '/v1/PostUser',
                    cache: false,
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: ko.toJSON(user),
                    success: function (data) {
                    //If user added successfully then below msg will be shown!
                    toastr.success('New account added successfully!', '');
                       
                    getUsersList();

                    }
                }).fail(
                         function (xhr, textStatus, err) {
                            //Failed to create new user!
                             toastr.error(err, 'Error')
                         });
            }
       
      //Add User: Cancel button function 
          self.CancelSave = function () {
                self.NewUserDiv(false);
                self.CreateNewUserButton(true);
            }


/////Edit User/////
        
      //Edit Button Funtion
        self.EditBtn = function (user) {
            self.user(user);
            self.NewUserDiv(false);
            self.CreateNewUserButton(true);
        }

      //Ajax post for update user details    
        self.UpdateUserInfo= function ()
        {
           
            var user = self.user();
           
            $.ajax({
                url: 'v1/PutUser',
                cache: false,
                type: 'PUT',
                contentType: 'application/json; charset=utf-8',
                data: ko.toJSON(user),
                success: function (data) {
                 toastr.success('Profile updated successfully!', '');

                 getUsersList();

                }
            }).fail(
                         function (xhr, textStatus, err) {
                             toastr.error(err, 'Error')
                         });
        }

     //Edit User: Cancel Button Function
        self.EditCancelBtn = function ()
        {
            self.user(null);
        }

 /////Delete user/////

       //Deleting the user record in the server using ajax post.
          self.DeleteUser = function (user)
           {
            var userId = user.UserId;
            
            $.ajax({
                url: '/v1/DeleteUser/'+userId,
                type: 'DELETE',
                success: function (data) {
                toastr.success('User deleted successfully!', '');
                getUsersList();
                }
            }).fail(
                        function (xhr, textStatus, err) {
                          toastr.error(err, 'Error')
                    });
        }


    };

    ko.applyBindings(new userViewmodel());

});


View:

       Now, open your view "Index". Add required scripts in the view.
    
   <script src="~/Scripts/knockout-3.1.0.js" type="text/javascript"></script>
   <script src="~/KOViewModels/UserViewModel.js" type="text/javascript"></script>

 
And if you want toastr messages then add below script and styles. Otherwise skip the below scripts.
  
 <script src="~/Scripts/toastr.min.js" type="text/javascript"></script>
  <link href="~/Content/toastr.min.css" rel="stylesheet" />


I have adding, updating and deleting the list of records using KO. We can do add, update and delete the records in single view without refreshing the page. This is wonderful feature we have in KO.

Display a KO List:
     First, we are applying the JSON array data to 'users' KO array. Then loop the array. Follow the below HTML code to display list of records.

 <div class="col-md-6" style="padding-top:10px">

     <div class="table-responsive">
       <span style="color:blue; float:left"><b>Users</b></span>

         <button type="submit" style="float:right" class="btn btn-primary btn-xs" data-bind="click: $root.CreateUserbtn, visible: CreateNewUserButton()">Add New User</button>
                
            
            <table id="user" data-bind="visible: users().length > 0" class="table table-hover" width="500">
                <thead>
                    <tr>
                        <th style="display:none;">
                            No.
                        </th>
                        <th>
                            Name
                        </th>

                        <th>
                            Email
                        </th>

                        <th>
                            City
                        </th>

                        <th>
                            State
                        </th>
                        <th></th>

                    </tr>
                </thead>
                <tbody data-bind="foreach: users">
                    <tr>
                      <td data-bind="text:UserId,uniqueName:true" style="display:none;"></td>
                      <td data-bind="text: FullName, uniqueName:true"></td>
                      <td data-bind="text: Email, uniqueName:true"></td>
                      <td data-bind="text: City, uniqueName:true"></td>
                      <td data-bind="text: State, uniqueName:true"></td>

                      <td><button class="btn btn-primary btn-xs btn-mini" data-bind="click: $root.EditBtn">Edit</button>
                            <button class="btn btn-primary btn-xs btn-mini" data-bind="click: $root.DeleteUser">Delete</button>
                        </td>

                    </tr>
                </tbody>
            </table>
        </div>
    </div>





Create new record:
      Get the required fields for adding a new record. The data binded to respected object automatically when textbox is filled. Then data will be sent to the server. Follow the HTML code for creating a new record.

<div class="col-md-6">
  <div data-bind="visible: NewUserDiv()">
    <div>
      <div class="caption" style="padding-top: 10px; text-align: center">
           <span style="color:blue;text-decoration:underline">
            <b>Create New User</b></span>
       </div>
     </div>
   <div>
    <form role="form">
       <div class="form-group">
        <label for="FullName" class="col-md-3 control-label">User Name</label>
          <div class="col-md-9">
             <input type="text" class="form-control" data-bind="value:FullName" placeholder="Enter user name" required>
               <span class="help-block"></span>
          </div>
        </div>

         <div class="form-group">
           <label for="FirstName" class="col-md-3 control-label">First Name</label>
              <div class="col-md-9">
                 <input type="text" class="form-control" data-bind="value:FirstName" placeholder="Enter first name" required>
                     <span class="help-block"></span>
               </div>
         </div>
         <div class="form-group">
           <label for="lastName" class="col-md-3 control-label">Last Name</label>

             <div class="col-md-9">
               <input type="text" class="form-control" data-bind="value:LastName" placeholder="Enter last name" required data-content="last name">
                <span class="help-block"></span>
             </div>
         </div>

         <div class="form-group">
           <label for="email" class="col-md-3 control-label">Email</label>
             <div class="col-md-9">
                 <input type="text" class="form-control" data-bind="value:Email" placeholder="Enter email" required>
                      <span class="help-block"></span>
              </div>
         </div>

         <div class="form-group">
            <label for="phone" class="col-md-3 control-label">Phone</label>
               <div class="col-md-9">
                  <input type="text" class="form-control" data-bind="value:Phone" placeholder="Enter Phone Number">
                      <span class="help-block"></span>
               </div>
         </div>

         <div class="form-group">
            <label for="Address" class="col-md-3 control-label">Address</label>
               <div class="col-md-9">
                  <input type="text" class="form-control" data-bind="value:Address" placeholder="Enter Address">
                      <span class="help-block"></span>
               </div>
         </div>

         <div class="form-group">
           <label for="City" class="col-md-3 control-label">City</label>
              <div class="col-md-9">
                 <input type="text" class="form-control" data-bind="value:City" placeholder="Enter City">
                     <span class="help-block"></span>
               </div>
          </div>

         <div class="form-group">
           <label for="State" class="col-md-3 control-label">State</label>
              <div class="col-md-9">
                 <input type="text" class="form-control" data-bind="value:State" placeholder="Enter State">
                     <span class="help-block"></span>
               </div>
          </div>
       
         <div class="form-group">
            <div style="text-align:center">
                <button type="submit" class="btn btn-success" data-bind="click: $root.createUser" title="Save">Add</button>

                 <button type="submit" class="btn btn-danger" data-bind="click: $root.CancelSave" title="Cancel">Cancel</button>
            </div>
         </div>


        </form>
      </div>
   </div>
</div>




Update record:
Get the data and fill the fields. Its faster than others. Follow the HTML code for Update an record.

<div class="col-md-6">
    <div class="" data-bind="if: user">
        <div>
            <div class="caption" style="padding-top:10px; text-align:center">
                <span style="color:blue;text-decoration:underline">
                     <b>Update User Information</b></span>
            </div>

         </div>
    <div>
       <form role="form">
            <div class="form-group">
               <label for="FullName" class="col-md-3 control-label">User Name</label>
                    <div class="col-md-9">
                        <input type="text" class="form-control" data-bind="value:user().FullName" placeholder="Enter user name" required>
                             <span class="help-block"></span>
                     </div>
             </div>

            <div class="form-group">
                <label for="FirstName" class="col-md-3 control-label">First Name</label>
                <div class="col-md-9">
                   <input type="text" class="form-control" data-bind="value:user().FirstName" placeholder="Enter first name" required>
                        <span class="help-block"></span>
                 </div>
            </div>

            <div class="form-group">
               <label for="lastName" class="col-md-3 control-label">Last Name</label>
               <div class="col-md-9">
                  <input type="text" class="form-control" data-bind="value:user().LastName" placeholder="Enter last name" required data-content="last name">
                      <span class="help-block"> </span>
                </div>
             </div>

             <div class="form-group">
                <label for="email" class="col-md-3 control-label">Email</label>
                    <div class="col-md-9">
                       <input type="text" class="form-control" data-bind="value:user().Email" placeholder="Enter email" required>
                            <span class="help-block"></span>
                     </div>
              </div>

             <div class="form-group">
               <label for="phone" class="col-md-3 control-label">Phone</label>
                   <div class="col-md-9">
                     <input type="text" class="form-control" data-bind="value:user().Phone" placeholder="Enter Phone Number">
                         <span class="help-block"></span>
                   </div>
             </div>

             <div class="form-group">
                <label for="Address" class="col-md-3 control-label">Address</label>
                    <div class="col-md-9">
                       <input type="text" class="form-control" data-bind="value:user().Address" placeholder="Enter Address">
                            <span class="help-block"></span>
                    </div>
             </div>

             <div class="form-group">
                 <label for="City" class="col-md-3 control-label">City</label>
                      <div class="col-md-9">
                        <input type="text" class="form-control" data-bind="value:user().City" placeholder="Enter City">
                            <span class="help-block"></span>
                       </div>
              </div>

              <div class="form-group">
                  <label for="State" class="col-md-3 control-label">State</label>
                      <div class="col-md-9">
                         <input type="text" class="form-control" data-bind="value:user().State" placeholder="Enter State">
                               <span class="help-block"></span>
                       </div>
              </div>

                   
              <div class="form-group">
                  <div style="text-align:center">
                     <button type="submit" class="btn btn-success" data-bind="click: $root.UpdateUserInfo" title="Save">Update</button>

                     <button type="submit" class="btn btn-danger" data-bind="click: $root.EditCancelBtn" title="Cancel">Cancel</button>
                   </div>
               </div>


            </form>
         </div>
     </div>
 </div>


      We can easily display a list, create, update and delete an record using Knockoutjs in MVC. We need to work out few things in the start-up then it goes everything smoothly.

Have a nice day!!






Read More »