Chlodny series Day 12: Web Api Create

[Updated to Web Api RC]

In our quest to create a CRUD application we have completed the read and the delete portion.  In this article we will generate the create functionality.  For now I am using the jQuery Templates in the future I will be switching to something else.

First thing that needs to be done is to open up the CustomerController.cs in the web api and create a new method with the name of PostCustomer.  It will return an HttpResponseMessage and will look for a parameter of Customer.

To improve on the user experience I am first checking to verify if the customer currently exist.  Going back to my note above, I am doing this in case a user uses the reverse logic then the customer object will be placed in the correct method.

If the user does not exist we will call Entity Framework and execute SaveChanges().  We will then create our HttpResponseMessage and pass in the customer object and an HttpStatusCode.Created.  This is considered good practice for one to notify the contact that something happened and the ajax call can check that the return message was a 201.  jQuery’s ajax call mechanism can check for specific return messaged and conduct different actions.

An example might could be if the message is 201 display a message that says “Customer ID xxxxx has been successfully created.”  Since the customer object with the new ID back is being passed back, the message could display the correct ID.

Included in this HttpResponseMessage the Headers.Localtion with the RequestUri that will give the address to this new user.

The PostCustomer method should look similar to the following:

 // Create = Post
public HttpResponseMessage PostCustomer(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)
       {
           context.Customers.Add(customer);
           context.SaveChanges();

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

       return this.PutCustomer(customer);
   }
}

Now to update the HTML file.

  • Open jqueryUILocal.htm,
  • In the tools div add a new button to create a new customer.

It should look like this now:

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

Below the tools div

  • Add a form with the id of “newForm”
  • Add a title of “New Customer”
  • Add open and close fieldset
  • add an input of type submit and give it a value of “Save Changes”

If should look like this:

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

The last thing that needs to be done in the HTML (when I move off jQuery Templates I will move this out of the html).  we will add out template script.  This will go though the array and generate the fields and labels for the object (or model for those familiar with MVC) passed in.  This code looks like this:

<script id="edit-tmpl" type="text/x-jsrender">
  {{if $.isArray(value)}}
  <label>${label}</label>
  <ul>
      {{each(index, valueX) value}}
      <li><input type="text" class="ui-widget-content ui-corner-all" name="${name}" placeholder="${label}" value="${valueX}" title="${label}" /></li>
      {{/each}}
  </ul>
  {{else}}
  <label for="${name}">${label}</label>
  <input type="text" class="ui-widget-content ui-corner-all" id="${name}" name="${name}" placeholder="${label}" value="${value}" title="${label}" />
  {{/if}}
</script>

Now to wire it all the modules together.  Since this part the code is a little long I will post the example first for jQueryUIExampleLocal.js:

jQueryExample.NewCustomer = function() {
    $("#newCustomer").click(function() {
        var newCustomer = {
            FirstName: "",
            LastName: "",
            Address: "",
            City: "",
            PostalCode: "",
            State: "",
            Country: "",
            Email: "",
            Phone: "",
            Fax: "",
            Company: ""
        };

        $("#edit-tmpl").tmpl(meta(newCustomer)).appendTo(newForm.find("fieldset").empty());
        newForm.dialog("open");
    });

    $("[type=submit]").button();
    var newForm = $("#newForm").dialog({
        autoOpen: false,
        width: 350,
        modal: true
    }).hide().submit(function (event) {
        event.preventDefault();

        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 = {
            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,
            success: function (result) {
                $.observable(localCustomers).insert(result);
                customers.refresh();
            }
        });

        newForm.dialog("close");
    });
};
  • Add a new function of jQueryExample.NewCustomer=function(){
  • Add a click event and define the new customer object

Note: Edit is a little easier because we can use the object in the jQuery observable, this was the easiest way I found.  JSRender/JSView might offer an easier or dynamic option.

  • then select the #edit-tmp and pass into the template the newCustomer model
  • Append it to the newform fieldset
  • then add a call to the dialog(“open”)
  • Wireup the submit button
  • In the submit button grab the values of the form
  • Package those values in a object called sentData
  • Call $.ajax with the verb of POST and then the sentData.
  • Add a success function to the Ajax call.  If no errors are returned the new customer will be added to the observable object that the data grid is bound to.
  • Call a refresh on the customers collection
  • and finally close the dialog.
  • Add jQueryExample.NewCustomer() to the jQueryExample.jQueryWireUp function

Run the code, click the New Customer button and the following form should open.

CropperCapture[73]

Add some data and click save changes.  In the Grid the new customer should show up.

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