asp.net 5 / mvc 6 / model binder / angular - angularjs

I do not know because when I do a post by angular, objects are not populated, such as categories or status. Just the product.
However, note that the Request.Form list, the information is there.
The binder is not performed correctly.
What am I doing wrong?
Is it any web api configuration?
I've tried sending data via application/json, [frombody] ... I'm out of options.
Thanks in advance.
var product = {
id: 1,
name: "Name",
categories: [
{ id: 1, name: "name 1" },
{ id: 2, name: "name 2" }
],
status: { id: 1, name: "active" }
};
var config: ng.IRequestConfig;
config = { url: "", method: "POST", headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' } };
self.$http.post("api/produto", $.param(product), config)
.success(function () {
alert("OK");
});
[HttpPost]
public ProductInfo Post(ProductInfo item)
{
return item;
}
model image
request image

try this:
$http({
url: "api/produto",
method: "POST",
data: product,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});

Or you could use the shortcut method:
$http.post('api/produto', data).then(successCallback, errorCallback);

Here's what I would try
var product = {
id: 1,
name: "Name",
categories: [
{ id: 1, name: "name 1" },
{ id: 2, name: "name 2" }
],
status: { id: 1, name: "active" }
};
var config: ng.IRequestConfig;
config = { url: "", method: "POST", headers: { 'Content-Type': 'application/json;charset=utf-8;' } };
self.$http.post("api/produto", product, config)
.success(function () {
alert("OK");
});
What is different is that I send the actual JavaScript object and it will be serialized as JSON. Web API will be able to deserialize the JSON into a pure C# object.
Trying to match key/value pair is normally just madness on complex objects.

There was no way to do it.
Either I create a custom model binder, or I'll have the new web api 6 mvc always use the frombody and force the ship by json.
At least that's what I did with my tests.
It worked just sending json and using frombody.
The documentation, really changed bind the web api 2 for this new integrated model to MVC.

Related

Want to use angularjs resource object with action method

I want to make a search query to my server with angularjs resource object and i have written such an resource object;
app.factory('EcriDeviceListService', function ($resource) {
var Url = "http://localhost:60766/api/EcriDeviceLists/:id/:queryText";
return $resource(Url, { id: '#Id' },{ update: { method: 'PUT' },'search': { method:'GET', {queryText:''}})
});
with this code i want to make a search query like this;
EcriDeviceListService.search({queryText:'abc'})
http://localhost:60766/api/EcriDeviceLists/queryText=abc"
how should i configure my resource object.
Thanks.
You should configure $resource object like this:
$resource('http://localhost:60766/api/EcriDeviceLists/:id/:queryText', {
id: '#Id',
queryText: ''
}, {
update: {
method: 'PUT'
},
search: {
method: 'GET'
}
});

Extjs Store Getting Data from Post

Good Morning,
I have a search endpoint that I that works when I call it like this:
Ext.Ajax.request({
url: '/Search/False',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
params: 'Attribute:ClosedDT;Value:2014-12-16',
success: function(conn, response, options, eOpts) {
alert(conn.responseText);
},
failure: function(conn, response, options, eOpts) {
alert(conn.responseText);
}
});
I want to use a proxy to load it into a store directly. After much googling I have tried this and i get back a POST /Search/False?_dc=1418738135737 net::ERR_EMPTY_RESPONSE
See current code below:
var proxyDefinition = {
type : 'rest',
api : {
read : '/Search/False'
},
actionMethods : {
read : 'POST'
},
reader : {
type : 'json'
},
paramsAsJson:true
};
returnValue = Ext.create('Ext.data.Store', {
model: 'Mdl1',
proxy: proxyDefinition
});
returnValue.load({params: 'Attribute:ClosedDT;Value:2014-12-16'});
The params config needs to be an object, not a string. Extjs will encode it for you because of paramsAsJson: true.
You should use:
params: {
Attribute: 'CloseDT',
Value: '204-12-16'
}

ngResource: Send data in URL instead of body

I'm trying to save a object with ngResource this way:
var Tasks = $resource("http://example.com/task", {
task: {
id: '#id'
}
}, {
'save': {
method: 'POST',
params: {
key: "abc"
}
}
});
var task = new Tasks();
task.id = "123";
task.$save();
This is generating this URL:
http://example.com/task?task=%7B%22id%22:%22#id%22%7D&key=abc
Why is the "#id" string not getting replaced with the actual data? Why is the key parameter not showing up?
I would highly suggest you modify the api to not pass json strings, but if you absolutely have to you can do something like the following
var Tasks = $resource("http://example.com/task", {
task: '#json'
}, {
'save': {
method: 'POST',
params: {
key: "abc"
}
}
});
var task = new Tasks();
task.id = '123';
task.json = angular.toJson(task);

How does $resource in Angular work

If I have a url like this "http : // x.x.x.x:port"
app.factory("myservice", function($resource){
var res = function(){
return $resource("http://x.x.x.x:port/profile/:userID", {
{
getUserInfo: {
method: "GET",
params: {userID : "userNumber"},
headers:{
"Accept": "application/json",
"Content-Type": "application/json",
sessionID : "sesionIDNumber"
}
}
},
});
}
console.log( res.get("firstName") );//error GET http://myurl/myport/profile?0=l&1=a&2=s&3=t&4=n&5=a&6=m&7=e&reg=%7B%2…2Fjson%22,%22sessionId%22:%22b1bfa646-215e-4223-be8c-b53d578ba379%22%7D%7D 404 (Not Found)
});
If I want to get the user's infoes, what do I have to do?
You can use like this
app.factory("myservice", function($resource)
{
return $resource('http://x.x.x.x:port/profile/:userID/:sessionID', {
userID : '#userID'
sessionID: "#sessionID"
});
});
A best example is shown below
app.factory('Books', ['$resource', function($resource) {
return $resource( '/book/:bookId',
{ bookId: '#bookId' }, {
loan: {
method: 'PUT',
params: { bookId: '#bookId' },
isArray: false
}
/* , method2: { ... } */
} );
}]);
At this point it is really simple to send requests to the web service, that we build in the previous post.Everywhere it is possible to inject the Books service it is possible to write:
postData = {
"id": 42,
"title": "The Hitchhiker's Guide to the Galaxy",
"authors": ["Douglas Adams"]
}
Books.save({}, postData);
// It sends a POST request to /book.
// postData are the additional post data
Books.get({bookId: 42});
// Get data about the book with id = 42
Books.query();
// It is still a GET request, but it points to /book,
// so it is used to get the data about all the books
Books.loan({bookId: 42});
// It is a custom action.
// Update the data of the book with id = 42
Books.delete({bookId: 42});
// Delete data about the book with id = 42

"Suggest slug name" API call in ngResource in AngularJS/Express app

I want the user to be able to set the slug name (URL) for a document in my app, but also I need some control so users don't override each other. It needs to be a separate call (not integrated with create/update) so the user can get visual feedback on their own slug name suggestions.
Therefore I've created a suggestSlug API call that takes an optional slug parameter as seed for the final slug name.
This is what my Express routes looks like:
app.get('/api/projects/suggestSlug/:slug', projects.suggestSlug);
app.get('/api/projects/suggestSlug', projects.suggestSlug);
app.get('/api/projects', projects.list);
app.get('/api/projects/:id', projects.show);
Now, I want to extend ngResource on the client side (AngularJS) to make use of this API:
angular.module('myapp.common').factory("projectModel", function ($resource) {
return $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
});
How do I extend the ngResource client to use my new API?
This was my solution: adding a separate $http-based method to my projectModel:
angular.module('myapp.common').factory("projectModel", function ($resource, $http) {
var projectModel = $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
projectModel.suggestSlug = function (slugSuggestion, callback) {
$http.get(
'/api/projects/suggestSlug/' + slugSuggestion
).success(callback).error(function(error) {
console.log('suggestSlug error:', error);
});
};
return projectModel;
});

Resources