Jquery Ajax Call - Passing multiple parameters avoiding name dependant - asp.net-mvc-4

In my asp.net mvc 4 application I do an ajax call to a controller method that has below signature:
[HttpPost]
public ActionResult DoSomething(string param1, string param2)
Currently my ajax call is working and I know how to pass multiple parameters, see below:
$.ajax({
url: "/DoSomething/",
data: { param1: "this is param1", param2: "this is param2" },
type: 'POST',
dataType: 'json'
});
But the problem here is that ajax call is totally dependant on the name of the parameters of the controller method, I mean, when passing parameters in the ajax call to the controller method, those parameters must be named the same as in the controller signature so is there any way to avoid name dependant? for example, without indicating parameter name in the ajax call and put them in order so the controller method knows that first parameter passed corresponds to the first parameter, second parameter passed to the second one and so on...

you can pass a array
[HttpPost]
public ActionResult DoSomething(string[] param)
$.ajax({
url: "/DoSomething/",
data: $.param({ param : ["this is param1","this is param2"] }),
type: 'POST',
dataType: 'json'
});
for more info check the docs here http://api.jquery.com/jquery.param/

what if you tried declaring the post function this way;
public ActionResult DoSomething(string args[])
/* I'm not sure which language you're using on the asp side,
* but the default array passed to a function is usually `args`
*/
and then you can use all passed parameters as they are in an array, and you can pass any amount of parameters?

Have you tried this? jQuery supports arrays as data.
$.ajax({
url: "/DoSomething/",
data: { params:[ "this is param1", "this is param2" ]},
type: 'POST',
dataType: 'json'
});

Related

ASP.NET WebAPI FromUri URL Limit

I have a WebAPI method which takes in 3 parameters, two of them primitive data types and the 3rd one is a complex data type:
public HttpResponseMessage validateUser(string elementName, string checkPermission, List<AccessElement> accessGroups)
I'm making call to this WebAPI using Angular $http:
return $http({
method: 'get',
url: serviceUrlPrefix + '/api/v1/validateUser',
params: { 'elementName': CONSTANTS.UNAUTH_DATA_UI, 'checkPermission': CONSTANTS.CAN_READ , 'accessGroups': accessGroups }
})
Problem:
When $http request is made, the query string values are truncated as the complex datatype parameter accessGroups is relatively long. I read in one of the blogs that query string limit in IE is 2083 characters
Question 1:
In my scenario, I won't say that acessGroups object is too big as it is a collection of 10 records (having 4 columns). With the query string limit on each browser, its quite understandable that I would face this truncation very easily when we pass the complex data type. So if it is the case, I would like to understand what is the primary use of [FromUri].
Question 2:
I was able to get around this issue by making the controller method as
public HttpResponseMessage validateUser(string elementName, string checkPermission, [FroimUri]List<AccessElement> accessGroups)
And made a POST call to this method with "data" parameter
return $http({
method: 'post',
url: serviceUrlPrefix + '/api/v1/validateUser',
params: { 'elementName': CONSTANTS.UNAUTH_DATA_UI, 'checkPermission': CONSTANTS.CAN_READ },
data: { 'accessGroups': accessGroups }
})
What is the drawback in this approach, since I'm going for "POST" method from a normal "Get". Would it cause any additional overhead?
I believe the only drawback is not adhering to the REST design principles (POST should be used to create a resource according to REST paradigm).
In practical terms, I would use [FromBody] tag. That way, you can be certain you won't run into any length restrictions.

Partial update using ajax jquery and wcf odata service

I am trying to update a single value of a record in the database using PUT request from java script to my WCF oData service. The code for the calling the service is
var upda = { stat: $("#com_status_txt").val() };
upda = JSON.stringify(upda);
console.log(upda);
$.ajax({
type: "PUT",
contentType: "application/json; charset=utf-8",
url: "http://localhost:65401/sdrservice.svc/issues('" + sessionStorage.currentIssue + "')/stat",
data: upda,
dataType: "json",
success: function (result) {
//Some code goes here...
},
error: function (xhr, textStatus, errorMessage) {
console.log(JSON.stringify(xhr));
}
});
where sessionStorage.currentIssue is my id for the issue and i need to update the stat field in table.
But when I run this service I receive following error.
{"readyState":4,"responseText":"{\"odata.error\":{\"code\":\"\",\"message\":
{\"lang\":\"en-US\",\"value\":\"An error occurred while processing this
request.\"},\"innererror\":{\"message\":\"A top-level property with name 'stat'
was found in the payload; however, property and collection payloads must always
have a top-level property with name value' .
\",\"type\":\"Microsoft.Data.OData.ODataException\",\"stacktrace\":\" at
Microsoft.Data.OData.JsonLight.ODataJsonLightPropertyAndValueDeserializer.
<>c__DisplayClassc.ReadTopLevelPropertyImplementation>b__5(PropertyParsingResult propertyParsingResult, String propertyName)\\r\\n at
Microsoft.Data.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(Duplic
atePropertyNamesChecker duplicatePropertyNamesChecker, Func`2
readPropertyAnnotationValue, Action`2 handleProperty)\\r\\n at
Microsoft.Data.OData.JsonLight.ODataJsonLightPropertyAndValueDeserializer.ReadTo
pLevelPropertyImplementation(IEdmTypeReference expectedPropertyTypeReference, DuplicatePropertyName
Here the message A top-level property with name 'stat' was found in the payload; however, property and collection payloads must always have a top-level property with name value' is confusing when I am not passing any collection just a key/value pair. My json representation for data is
{"stat":"Query"}
Json representation is a problem here change it to
{ "value": "Query" }

MobileFirst Platform JavaScript adapter can't get the parameters through WLResourceRequest

I'm using mobilefirst platform v7, and I send post request using the WLResourceRequest/sendFormParameters api, however, I can't get the submitted parameters from js adapter side...
belows are sample code:
var resourceRequest = new WLResourceRequest("adapters/businessAdapter/flightsearch", WLResourceRequest.POST);
var params={
"flightNum":'mu8899',
"departCity":'SHA',
"destCity" :'PEK'
};
resourceRequest.sendFormParameters(params).then(
callSuccess,
callFailure
);
js adapter code:
function flightsearch(params) {
WL.Logger.info("get params "+params);
var input = {
method : 'post',
returnedContentType : 'json',
path : 'restapi/api/flightsearch',
body :{
contentType: 'application/json; charset=utf-8',
content:params
},
headers: {"Accept":"application\/json"}
};
return WL.Server.invokeHttp(input);
}
The syntax you used is fine for Java adapters.
However, in the case of JavaScript adapters, procedure parameters are handled differently.
First, your adapter procedure should define the parameters that it expects:
function flightsearch(flightNum, departCity, destCity) {
///
}
Secondly, this procedure will be triggered using an HTTP GET or POST with a single parameter called params which needs to contain an array, representing all the procedure parameters in the correct order:
params:["mu8899","SHA","PEK"]
Now using JavaScript, this would translate to:
var resourceRequest = new WLResourceRequest("adapters/businessAdapter/flightsearch", WLResourceRequest.POST);
var params=[
'mu8899',
'SHA',
'PEK'
];
var newParams = {'params' : JSON.stringify(params)};
resourceRequest.sendFormParameters(newParams).then(
callSuccess,
callFailure
);
As you can see, we first build the JSON array (note, array not object) in the correct order, then we convert it to String and send it to the adapter with the parameter name 'params'.

How to call web api Controller method with two parameters using angularjs

I am pretty new in angularjs and I've looked around to try to find some posts on this and there are many but none that address my specific question (that I could find).
It is as simple as that, I want to send two parameters through angularjs ($http POST) where my first parameter is a json of class object and second is int. What I tried :
var url = '../Request/'+ id;
$http({
method: 'POST',
url: url,
data: Data
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
debug.error(data);
deferred.reject('An error occured while saving the request');
});
In my web api Controller I have :
[POST("Request/{id}")]
public bool SaveRequest(Data data, int id)
{
...
...
}
When I send only Data it works for me but when I tried to add Id and Data both it won't work. Please let me know what needs to be done for the same, Thanks.
Have you tried using [FromBody] attribute like this
[POST("Request/{id}")]
public bool SaveRequest([FromBody] Data data,[FromUrl] int id)
{
...
More info on parameter binding

Differences between $.ajax type put and model.save in backbone.js?

There seems to be some differences between saving a model using this.model.save() and using jquery ajax type PUT?
I have the following method in my api controller
public void Put(string id, [FromBody]IContent value) {
// save
}
I have also enabled TypeNameHandling on JSON formatter serializer setting like this:
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
If I PUT some data using jquery ajax like this
$.ajax({
url: "/api/page/articles/1",
type: "PUT",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({"$type": "BrickPile.Samples.Models.Article,BrickPile.Samples","id": "articles/1", "heading": "Some heading..." })
});
my object binds correct in the put method but when I try to save my object using model.save() in backbone the input value is null and it cannot bind the object?
This is how I do it:
this.model.set({ heading: 'foo' });
this.model.save();
the request headers seem to look ok and the payload is seems to be JSON, at least if I look in firebug. It's also possible to PUT some data to my api using fiddler with the same payload but not if I copy the payload source from firebug see: http://cl.ly/Nked
Can anyone explain what I'm doing wrong here?
Without knowing more about your model implementation it is hard to say for sure. One thing I can see from your firebug screenshot is that the id attribute is being passed as "articles/1" which is unusual for standard Backbone. If you were saving a model object then the id would normally be "1". So a model.save() would generate a HTTP PUT to articles/1 and pass the json as something including {"id":"1", ... }. The Backbone.sync documentation has more details on the default behaviour.