Thursday, August 8, 2013

Doing an AJAX (Javascript, JQuery) post using MS MVC on the server

On the Javascript side, the code looks like this:

    var url = window.WEBROOT + 'InventoryItem/_Data_UpdateInventoryTransaction';
    var it = {};  // \Model\ActivityTypes\ActivityHistoryInventoryTransaction
    it.InventoryTransactionId = id;
    it.UsageQuantity = usageQuantity;
    it.LocationId = gridLocationId;
    $.ajax({
        type: 'POST',
        url: url,
        data: it,
        async: true
    });

What's going on here?

The URL says where to go on the server.   window.WEBROOT is a variable set as the page is loading, in the file shared/_Layout.cshtml, which runs every time and is provided by Microsoft.  (This is my addition to the page, of course).  Now I don't have to hard code the path through the website to the root of this web.

it is a Javascript object that mimics the structure of a class with the c# in the mvc world.  I assign values to attributes that match the c# names, and then the object is passed in the ajax call, later in the code.

The $ indicates the start of the jquery ajax call, and we pass it asynchronously.  In this case, I do not need to wait for returned data.

On the server side, in the InventoryItem controller, I have a method called _Data_UpdateInventoryTransaction which takes an InventoryTransaction object.  This object is the defined in exactly the same way as the IT object above.  At that point, I can pass the object to a lower layer, or I can use any of the data elements.

No comments:

Post a Comment