Chlodny series Day 13: Web Api Update

[Updated Web Api RC]

The last part of the local CRUD application is update.  We will be following a similar pattern that was conducted in Day 12.

Open CustomerController.cs and create a new method named PutCustomer that returns a HttpResponseMessage.    In order to improve the user experience, check the passed in customer ID.  Check the database to see if the user exist.  If it does not, it will pass the customer object off  the post method.  If the customer object does exit, it will update the existing customer and save the changes.  If the update is accepted it will pass back the updated customer object and an accepted http response back to the client.

The PutCustomer method should look similar to the following:

// Update = Put
public HttpResponseMessage PutCustomer(Customer customer)
{
   using (var context = new ChinookContext())
   {
      Customer request = null;

      if (customer.CustomerId != 0)
      {
          request = context.Customers.Single(c => c.CustomerId == customer.CustomerId);
      }

      if (request == null)
      {
          return this.PostCustomer(customer);
      }

      // todo this has to have an easier way.  Customer.Attach throws an error
         request.FirstName = customer.FirstName;
         request.LastName = customer.LastName;
         request.Address = customer.Address;
         request.City = customer.City;
         request.PostalCode = customer.PostalCode;
         request.State = customer.State;
         request.Country = customer.Country;
         request.Fax = customer.Fax;
         request.Email = customer.Email;
         request.Company = customer.Company;

         context.SaveChanges();

         var response = Request.CreateResponse(HttpStatusCode.Accepted, customer);
         response.Headers.Location = new Uri(Request.RequestUri, string.Format("Customer/{0}", customer.CustomerId));
         return response;
   }
}

Next a new button to update the selected customer needs to be added to jqueryUILocal.htm.

In the tools div add a new button to the tools div named Edit Customer.

This div should not look like this:

<div id="tools" class="tools">
        <button id="newCustomer">New Customer</button>
        <button id="editCustomer">Edit Customer</button>
        <button id="removeCustomer">Remove Customer</button>
        <button id="clearSelection">Clear selection</button>
</div>

For now below the tools div we will add a new form with the id of editForm.  You can copy the previously created newForm and change the label.  This should look like this:

<form id="editForm" title="Edit Customer">
        <fieldset>
        </fieldset>
        <input type="submit" value="Save changes" />
</form>

In jQueryUIExampleLocal.js it is time to wire up the edit button.  Create a new function with the name of jQueryExample.EditCustomer.  Below is the example followed by the explanation.

jQueryExample.EditCustomer = function() {
    var customer;
    $("#editCustomer").click(function() {
        if (!selected.length) {
            alert("None selected");
            return;
        }
        customer = selected[0];
        $("#edit-tmpl").tmpl(meta(customer)).appendTo(editForm.find("fieldset").empty());
        editForm.dialog("open");
    });
    $("[type=submit]").button();
    var editForm = $("#editForm").dialog({
        autoOpen: false,
        width: 350,
        modal: true
    }).hide().submit(function(event) {
        event.preventDefault();

        var customerId = $("#CustomerId").val();
        var firstName = $("#FirstName").val();
        var lastName = $("#LastName").val();
        var address = $("#Address").val();
        var city = $("#City").val();
        var postalCode = $("#PostalCode").val();
        var state = $("#State").val();
        var country = $("#Country").val();
        var email = $("#Email").val();
        var phone = $("#Phone").val();
        var fax = $("#Fax").val();
        var company = $("#Company").val();

        var sentData = {
            CustomerId: customerId,
            FirstName: firstName,
            LastName: lastName,
            Address: address,
            City: city,
            PostalCode: postalCode,
            State: state,
            Country: country,
            Email: email,
            Phone: phone,
            Fax: fax,
            Company: company
        };

        $.ajax({ 
            type: 'POST', 
            dataType: 'json', 
            url: 'http://localhost:60025/api/customer', 
            data: sentData }

    );
        $.observable(customer, localCustomers).property(serializeForm(this));
        customers.refresh();
        // TODO hide tooltip
        editForm.dialog("close");
    });
};
  • Click event is wired to the edit customer button.
  • Then we verify that a customer has been selected, if not an alert box is displayed
  • The selected customer is passed to the template and the form is opened.
  • After the data has been updated, the submit button wraps up the data
  • An Ajax call with the verb put is sent to the server.
  • The page collection is then updated and then refreshed

We now have a fully working CRUD application that will work on the same domain as the web server.  In the next we series I will demonstrate utilizing cross domain techniques.

Advertisements
This entry was posted in MVC, Web and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s