WebApi 2.1 + Backbone.js 1.1.2: sync everything at once - javascript

Disclaimer: I'm a WebApi/BackBone beginner, so the question might be a bit odd since there is a lot about these components I don't really know and/or understand.
It would be nice to have the possibility to issue just ONE sync() call to the server to synchronize everything. I mean, when I saw sync() method, at first I thought it's used like that, but as soon as I saw the "create", "update", "delete" params I realized it's not. But there is an underlying problem related to Backbones default implementation for DELETE.
I've learned that classic implementation of Backbone.js allows one deleted (destroyed) model at a time to be sync'ed to the server. Created/modified (POST/PUT operations) content is sent in the request body itself, so the JSON is filled with the data and deserialized by WebApi model binding on the server. It doesn't work like that for DELETE, since body is always empty and reference to the model is made by URL parameters in query string. So, I guess to achieve that functionality, the request for DELETE should be sent in body as well as for POST/PUT.
Is there a possibility to change all of this behavior AND make it work with WebApi? I googled for that stuff already, but can't find anything to point me to the right direction.
What I have until now is a Backbone model, collection and a view set up.
Backbone.sync("create", this.collection); is called by the view on button click.
On the server side there is a WebApi controller set up with scaffolded methods:
// GET
public IEnumerable<Ponuda> Get()
{
return _storageService.GetPonude().ToList();
}
// GET
public Ponuda Get(int id)
{
return (Ponuda)_storageService.GetPonuda(id);
}
// POST
public void Post([FromBody]IEnumerable<Ponuda> value)
{
_storageService.CreatePonude(value);
}
// PUT
public void Put([FromBody]IEnumerable<Ponuda> value)
{
_storageService.ModifyPonude(value);
}
// DELETE
public void Delete(IEnumerable<int> value)
{
_storageService.RemovePonude(value);
}
EDIT: I'm reading about Marionette.js and it seems to offer standard model/view related functionalities out of the box. However, I still can't see the possibility to save/sync e.g. the entire modified collection at once.

To sync all contents at once :
For POST and PUT Http methods, you can use Backbone.Sync API.
For DELETE, you can directly use the ajax API for deleting the content in the server and use Backbone Collection remove API to delete the content in the client side.
I have written skeleton code which demonstrates on how to achieve the functionality:
var PersonModel = Backbone.Model.extend({
url: '/demo',
defaults: {
"id": 0,
"name": "",
"age": 0
}
});
var PersonCollection = Backbone.Collection.extend({
url: '/demo',
model: PersonModel
});
var model1 = new PersonModel({"name": "John", "age": 30});
var model2 = new PersonModel({"name": "Joseph", "age": 30});
var collection = new PersonCollection();
// model will be added locally on client side. It will not sync to the server.
collection.add(model1);
collection.add(model2);
// POST. This will create both the models together using a single REST API request.
Backbone.sync('create', collection);
// PUT. This will update both the models together using a single REST API request.
Backbone.sync('update', collection);
// Extract the model ids to be deleted
var modelIds = [model1.get('id'), model2.get('id')];
$.ajax({
method: 'DELETE',
url: '/demo',
data: JSON.stringify(modelIds), // This will add ids to the request body
contentType: 'application/json',
success: function() {
// On successful deletion on server end, delete the models locally.
collection.remove([model1, model2]);
}
});
Regarding the WebApi, since I have not worked on it, will not be able to guide you. Having worked on Spring Rest API, I can tell you above functionality should work with the WebApi.

Related

How does an MVC 5 view request with parameter data a controller to launch another view

This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method.
I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):
$(document).ready(function () {
$('#PurchaseOrderLineItemAddId').click(function () {
var aPurchaseOrderViewModel = #Html.Raw(Json.Encode(Model));
var selectedVendorText = $('#ddlvendors option:selected').text();
var selectedVendorValue = $('#ddlvendors option:selected').val();
var LineItemReqJsonObj = {};
LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
LineItemReqJsonObj.VendorText = selectedVendorText;
LineItemReqJsonObj.VendorValue = selectedVendorValue;
var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';
$.ajax(
{
type: "POST",
//data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
//data: aPurchaseOrderViewModelStr,
data: dataToPass,
url: '#Url.Action("PurchaseOrderAddItem")',
contentType: "application/json; charset=utf-8",
datatype: "json"
})
.done(function (aNewLineItemViewModel) {
AddNewLineItemReceived(aNewLineItemViewModel);
})
.fail(function (xhr) {
alert('error', xhr);
});
});
});
Below is the action method in the controller which receives the above ajax request:
[HttpPost]
public ActionResult PurchaseOrderAddItem(LineItemReqJsonObj aLineItemReqJsonObj)
{
LineItemViewModel aLineItemViewModel = new LineItemViewModel();
aLineItemViewModel.PurchaseOrderId = aLineItemReqJsonObj.PurchaseOrderId;
aLineItemViewModel.VendorId = Convert.ToInt32(aLineItemReqJsonObj.VendorValue);
return View(aLineItemViewModel);
}
Below is the class in the controller which gets data filled into it as it is passed in from the JavaScript:
public class LineItemJsonObj
{
public string PurchaseOrderId {get;set;}
public string VendorText { get; set; }
public string VendorValue { get; set; }
};
The below diagram illustrates what I am trying to do:
As the diagram shows, I am unable to get the PurchaseOrderAddItem View to be shown. How do I get the PurchaseOrderAddItem View to show, receiving parameter data, after the PurchaseOrder View has invoked the PurchaseOrderAddItem Action From the controller?
Thanks in advance.
-- UPDATE 2/17/2020 1:38PST--
I am probably incorrect in thinking the controller could start the PurchaseOrderAddItem View which when
closed could get the resulting new model data somehow back to the PurchaseOrder
View with the JavaScript that started this.
I am beginning to think this approach using the JavaScript $Ajax to
reach the controller is not the right way to do this. I'm checking now to see
if maybe I should of just loaded another web page from the PurcahseOrder View
with parameter data to create a new PurchaseOrderAddItem View. The challenge here though would
be to probably pack up the entire PurchaseOrder view model data to go with the
PurchaseOrderAddItem View request. If I have the entire PurchaseOrder View Model
data when I exit the PurchaseOrderAddItem View I will be able to load a new
PurchaseOrder View and pass it all the data that was in the first instance so it
is repopulated to include the newly added line items. I'm not sure this is
the right way to do this. I have not seen any examples yet of how this type of
application view presentation problem is handled. I would appreciate it if anyone can
point me to any internet articles that perhaps cover how to design this type of
MVC application. This is very easy to do in desktop apps but web development
with MVC makes this very different and needing a lot more work than something
in WPF or WinForms.
The solution for me in this case was to use the TempData dictionary object to help transport data from the PurchaseOrder View request to the LineItem View and back. There is no sensitive data in this data transport so using TempData should be fine. Additionally, to launch the LineItem view to create a new Line Item worked better for me to just us the standard submit action from within an Html.BeginForm block. The standard post operation provided by the submit button is what I used in this case rather than a button to run $.Ajax code in a JavaScript. Ajax was really not needed in this case since the whole PurchaseOrder View was to be replaced by the LineItem create view.

How to force a POST request when saving a model?

I need to make a POST to a server-side API. I must send an id key into the request body to the server.
I use a Backbone model. But when I do:
myModel.set("id", somevalue)
myModel.save()
The network request that is fired is : URL/someValue [PUT]
Backbones doesn't do a POST but a PUT and appends the id to the url.
So I just want to pass an id key to the server without Backbone noticing.
From Backbone's doc:
Backbone is pre-configured to sync with a RESTful API.
[...]
The default sync handler maps CRUD to REST like so:
create → POST /collection
read → GET /collection[/id]
update → PUT /collection/id
patch → PATCH /collection/id
delete → DELETE /collection/id
A new entry doesn't have an ID, so if you give an ID to the model before saving it, Backbone defaults to a PUT request because it thinks you want to save an existing entry.
How to make a POST request with an id?
Choose one of the following solutions.
Stick to a RESTful API
This one is the obvious one. If you can, stick to the standard.
Change the API to handle PUT/PATCH requests and only use POST on creation. Make the API endpoint take the ID from the URL.
RESTful API best practices
Pass the type option1
Simple and works really well for a one-off situation.
Every options passed to save (or fetch) overrides the options the sync function defines by default and passes to jQuery.ajax function.
Backbone sync source
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
var url = model.url(); // get the url before setting the `id`
model.save({
id: somevalue
}, {
url: url, // fix the url
type: 'POST' // choose the HTTP verb
});
Fixing the url that the model uses is simple, you have also some choices:
pass the url option (like above)
override the url function of the model
Overriding the url function (source) works well for situation where every call should use a specific url, without the default id appended to it.
var MyModel = Backbone.Model.extend({
url: function() {
return _.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
}
});
Set the idAttribute on the model
This depends on what the id you're trying to pass means in the data.
Backbone Model uses "id" has the default id attribute name. You can specify a different name by overriding the idAttribute property of the model. Whatever the name, it is always automatically made available through the model.id property.
Now, assuming the id attribute isn't related to this model and this model's real id attribute name is something like UID, you could change the idAttribute of the model to reflect the real name of the attribute (or it could even be a string that's never going to be an attribute).
var MyModel = Backbone.Model.extend({
idAttribute: 'UID',
});
Now, the id attribute is not considered an id for the current model, and model.isNew() will return true, sending a POST request to create it on save.
Change the sync/save function behavior
If the API you're using is not RESTful, you can adjust the behaviors by overriding the sync function. This can be done on the model or collection, or on the Backbone.sync function which is used by default by the collections and models.
For example, if you wanted to make every request use POST by default for MyModel class:
var MyModel = Backbone.Model.extend({
sync: function(method, model, options) {
return Backbone.sync.call(this, method, model,
_.extend({ type: 'POST' }, options));
}
});
You could do something similar with only the save function to let the fetch do its GET request as usual.
Use the emulateHTTP setting2
If you want to work with a legacy web server that doesn't support
Backbone's default REST/HTTP approach, you may choose to turn on
Backbone.emulateHTTP. Setting this option will fake PUT, PATCH and
DELETE requests with a HTTP POST, setting the X-HTTP-Method-Override
header with the true method.
[...]
Backbone.emulateHTTP = true;
model.save(); // POST to "/collection/id", with "_method=PUT" + header.
Do not override isNew
Has this model been saved to the server yet? If the model does not yet
have an id, it is considered to be new.
Some other answers on this site suggest overriding the isNew function. Don't. The function has its purpose and overriding it to force a POST request is a poor hack, not a solution.
isNew is used internally but can also be used by your code or other libraries and Backbone plugins.
1 While I did not take this from stack overflow, it was already an answer by Andrés Torres Marroquín on a similar question.
2 Taken from Maanas Royy's answer.

Dynamically load my 'IDs' into my Backbone Collection?

Ok, I have got this working with answers posted on another question here, but I am trying to do something a little more. I have a Backbone set up as follows,
var MyModel= Backbone.Model.extend();
var MyCol = Backbone.Collection.extend({
model : MyModel,
url: '/GetData/2',
parse: function(response) {
return response;
}
});
var stuff = new MyCol;
stuff.fetch({
success: function (collection, response) {
console.log(response);
}
})
Now this code fully works. Now to explain, the URL is set with PHP Slim, which returns JSON encoded data, where will be four key/pair groupings, for example:
<code> { id; XX, data: XX, another:XX, last:YY } </code>
This data is being received form a database, now how should I do this dynamically? By that I mean that on the URL' line in my collection, it passes 2 as the current ID. How can I get backbone to call each ID I need, there are currently 6 listing in the database. So I need it display/console log (currently for testing) all 6 inputs, so how would I change that ID input to 1-6? Should I just use a for loo? I really want something that will not need to change if say lists are removed form the database or more are added?
The end aim is for this JSON data is for it to load into my Backbone view, which is a template for a form.
All help most welcome,
Thanks
Glenn
P.S Sorry if my spelling is off I am dyslexic, also may not have explained things right, so let me know and I will improve my wording, thanks.
EDITS
This is what I am working with now ::
var AdminModel = Backbone.Model.extend({
defaults: {},
urlRoot: '/GetData'
});
var AdminColModel = Backbone.Collection.extend({
model : AdminModel,
url: '/',
parse: function(response) {
//console.log(response);
return response;
}
});
var stuff = new AdminColModel;
stuff.fetch({
success: function (collection, response) {
console.log(collection);
}
})
This does not console log anything at all? But the PHP is set up and working fine, so when you go to /getData you get a whole list if all the rows in the database. When you view /getData/X <- X is the id number, that will return just that rows ID data.
Glenn
You should not make an individual request for each model in your collection at the collection level. The url you have set for your collection should request all of the models by default. So instead of it being:
'/GetData/2'
It should instead be:
'/GetData'
Then on the server side you should ensure that the GetData action returns all MyModels.
You can then write overrides for GetData that take parameters to either return an individual model, or filter the results. You will be particularly interested in the individual model retrieval, which should be the URL used at the model level. in fact, you already have this action, as you are using it (incorrectly) to retrieve the collection. This is the action associated with the /GetData/2 URL. This action should be the one used when you call fetch inside the model, not the collection.
Hopefully this helps.
Post Edit
Adding some code to assist.
var AdminModel = Backbone.Model.extend({
urlRoot: '/GetData'
});
var AdminCollection = Backbone.Collection.extend({
model : AdminModel,
url: '/GetData'
});
var wholeCollection= new AdminCollection();
// the fetch method on the collection uses the AdminCollection.url property
wholeCollection.fetch({
success: function (collection) {
console.log(collection); // will output collection object to console
}
});
// this model does not exist in any collection
var modelOutsideCollection = new AdminModel({}, { id: "2" });
// because the model is not in a collection, fetch uses the AdminModel.urlRoot proeprty
modelOutsideCollection.fetch({
success: function (model) {
console.log(model); // outputs a single model with id of 2 to collection
}
});
So... The way you seem to be doing things is going to make it really hard (if even possible) to work with Backbone.
What you should have is an API endpoint (e.g.) "getData" that will return all models:
[
{id: 1, name: "asdflj"},
{id: 2, name: "lsdfkjg"},
// etc.
]
Then, you define "getData" as the collection's url. For each model in the collection, Backbone will automatically compute the model instance's url as (e.g.) "getData/2" (if the model's id is 2).
In other words, you'd need to change your API to have:
getData -> return all models
getData/2 -> return model with id 2

Ember.js Search Model Verbs

The tutorials & guides that I've found suggest that Ember.js models are very data centric, in that you have data in the browser that is persisted to the server and/or a model is filled with data from the server.
How about something that is more verb centric? For example, my case is that, so far, I have a "Search" model, where a search has a query, a state ("beforesearch","duringsearch", etc...), and, hopefully, some results. I want for the search to then "runQuery", which fires off an ajax request to the server, which returns and fills the model with the results, and changes its state to "aftersearch".
What's the best way of handling such verbs on models? Should the "runQuery" go via ember-data, or just manually fired off using $.ajax or similar? Am I maybe thinking about models in the wrong way, and this should actually go via a controller?
Edit: After reading up a bit on REST, I think what I'm wanting is to POST to a "controller" resource. So, for example:
POST: /searches (to create a search)
POST: /searches/1/run (to execute search 1's "run" controller
Does Ember.js / ember-data have a recommended way of calling controller resources like this?
Ember-data is very oriented around using model objects that contain various information fields and relationships and are defined by a unique id. Half of my API is like what ember-data expects and half is like you described, it is more about data processing or performing a calculation than creating/retrieving/updating/deleting a data object that has an id. It doesn't make sense to treat these calculations the same and assign it an id and persist it in the database.
In my case, since I have both ember-data style data objects and calculation functionality I use a mix of ember-data and custom ajax requests. I have relational data stored that is retrieved by ember-data but I augment the models to include access to the calculation portions.
For example:
App.Event = DS.Model.extend({
name: DS.attr('string'),
items: DS.hasMany('App.Item'),
...etc...
searchData: null,
searchInEvent: function(data) {
var _this = this;
return $.ajax({
url: "/api/events/" + this.get('id') + "/search/",
dataType: 'json',
type: 'POST',
data: data
}).then(function(result){
_this.set('searchData', result);
});
}
});
App.Event is a normal ember-data model and is loaded by the router through the usual ember conventions, and as the various controllers need access to the search functionality they can access it through searchInEvent and searchData that were added to the model.

Backbone.js without REST using ASP .net webservice

(sorry for the english)
I have a ASP .net webservice that get data from a oracle database returning JSON data.
TestWebService.asmx/getUserData
I test this using simply ajax request with jQuery
$.ajax({
type:"POST",
data:"{}",
dataType:"json",
contentType:"application/json; charset=utf-8",
url:"TestWebService.asmx/getUserData",
success:function(data){
console.log(data.d);
}
});
This work.
But now i want to try use Backbone.js
The Application have this: User data, Articles and Buy Order where a Buy order is a collection of Articles, so i think in this models for Backbone
User = Backbone.Model.extend({})
Article = Backbone.Model.extend({})
ArticleCollection = Backbone.Collection.extend({})
BuyOrder = Backbone.Model.extend({})
BuyOrderCollection = Backbone.Collection.extend({})
The Views are just 2. A Form where i show the User Data and inputs to add Articles and create the Buy Order and a Visualize view to show the Buy Orders where the user can see an check the content of one buy order clicking in the code.
The UserData, and part of the Article Data are get from the service: (User Data like name and Article Data like code, description, price, etc).
¿How can i populate the Backbone models with this data?
Thanks in advance.
So, basically, you want to override Backbone.sync. It is the thing that is currently doing your RESTful stuff (GET/POST/PUT/DELETE) via the $.ajax function as well. See how it is implemented by default: http://documentcloud.github.com/backbone/docs/backbone.html#section-134
As you can tell, it is really quite simple... about 30 or so lines of code to map create/update/delete/read to post/put/delete/get in $.ajax.
Now that you have seen how they do it, you just implement your own using the same pattern:
Backbone.sync = function(method, model, options) {
// your implementation
};
Once you do that, you are golden. Your models will do all the CRUD that you want them to, abstracted through your implementation of Backbone.sync.

Categories