I have a WCF service hosted in Sharepoint 2010 (therefore no config file necessary --> ServiceHost Factory set to MultipleBaseAddressWebServiceHostFactory).
My service interface:
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
List<Course> GetAllCoursesByPerno(string empPerno);
My ajax call:
var input = $j("#perno").val();
$j.ajax({
type: "POST",
url: "/_vti_bin/Project/Service.svc/GetAllCoursesByPerno",
dataType: "json",
//data: input,
data: '{"empPerno": "' + input + '"}',
contentType: "application/json; charset=utf-8",
processData: true,
success: function (data) {
var courseData = data;
},
error: function (e) {
alert(e.statusText);
}
});
My method:
public List<Course> GetAllCoursesByPerno(string empPerno)
{
.
.
.
.
}
I get a 400 Bad Request each time. I've tried every which way to compose the data;
data: '{"empPerno": "' + input + '"}',
data: JSON.stringify({ empPerno : input }),
But no cigar. Any help would be appreciated!
Thanks
Use Microsoft ajax library for calling.
This also avoid DateTime deserializing issues
Sys.Net.WebServiceProxy.invoke('/_vti_bin/YourSubfolder/SearchService.svc',
'EmptyMethod',
false,
{data: 'client data'},
function () {
console.log('Success', arguments);
},
function () {
console.log('Eroor', arguments);
}, this);
Related
I am sending a file input in FormData to a web api as below. The api method expects one additional parameter as well but the below code works only without the parameter in api. How can I send the additional parameter to the api.
Thanks for any suggestions!
<div>
<label for="add">Add Customer</label>
<input type="file" onchange="AddCust(event)" />
</div>
function AddCust(event)
{
Add("testtype", event.target.files[0]);
}
function Add(type, file)
{
var imageData = new FormData();
imageData.append("myfile", file);
$.ajax({
url: _uri + '/party/Add',
type: 'POST',
enctype: 'multipart/form-data',
data: imageData,
cache: false,
contentType: false,
processData: false,
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data) {
$("#log").append("Add - Success " + data.toString() + "</br>");
},
error: function (xhr, ajaxOptions, thrownError) {
$("#log").append("Add - Error " + xhr.responseText + "</br>");
}
});
Web API:
[HttpPost]
public async void Add(string customertype)
{
var provider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data"));
await Request.Content.ReadAsMultipartAsync(provider);
}
Found out that below does not work.
url: _uri + '/party/Add/testtype'
It has to be specified in url
url: _uri + '/party/Add?customertype=' + 'testtype'
I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.
I can pass a model and string parameters into the controller, however, ints are not working for me.
I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.
Is there a way I can avoid this and just pass an int?
below is the code I am trying.
[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
//DO stuff with int here
}
here is the js.
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
The objId is always 0 in the controller.
I have tried this without doing JSON.stringify(data) as well with no result.
I have also tried all the different form attribute variations.
Try to use contentType as 'application/x-www-form-urlencoded':
var data = { objId: 1 };
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
Then remove the [FromBody] attribute in the controller
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//Do stuff with int here
}
I believe your issue could be that you are passing an object to the api, but trying to turn it into a primitive. I know there is already a chosen answer, but give this a whirl.
var data = { };
data["objId"] = 1; //I just wanted to show you how you can add values to a json object
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
You create a model class
public class MyModel {
public int ObjId {get;set;}
}
Your controller should expect one of these
[HttpPost]
public JsonResult PassIntFromView([FromBody] MyModel data)
{
//DO stuff with int here
}
JSON has a preference for strings not integers. You are better off to use JSON.stringify(data) to parse to your controller, convert that to a integer in the controller, then parse the string that was returned as:
var data = { objId: 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',//asp.net - url: 'api/controllerName/controllerFunction'
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
var result = JSON.parse(data);
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Try this:
var data = { "objId": 1};
$.ajax({
url: '#Url.Action("PassIntFromView", "ControllerName")',
data: data,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
Your controller:
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//DO stuff with int here
}
Js
var data = { "objId": 1};
$.ajax({
url: "ControllerName/PassIntFromView",
data: data,
type: "POST",
dataType: 'JSON',
success: function(data.result!=null) {
console.log(data.result);
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
I got it working like this
let numberFour = JSON.stringify(4);
$.ajax({
.......
.......
data: numberFour,
type: "POST",
dataType: 'JSON',
contentType: "application/json",
......
........
});
With my code i get a internal Server error:
#using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
#Html.AntiForgeryToken()
}
<script>
function Like(id) {
var requestData = {
profileId: id,
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
};
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: JSON.stringify(requestData),
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }
If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?
I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}
/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC
function Like(id) {
var form = $('form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: { __RequestVerificationToken: token, profileID: id },
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
I am using WAP API, but don't know how to use ajax connect into the aaa method. Please help. same the ajax method cannot match [FromBody]Guid[] Ids, but how
[Route("aaa")]
[HttpPost]
public IHttpActionResult aaa(Guid teamId, [FromBody]Guid[] Ids)
javascript
var routeIds = new Array();
routeIds.push('EEBEEEDF-41F2-4931-41F2-362DDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
var team = { id: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06" };
var tmp = JSON.stringify({ teamId: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06", '': routeIds });
var path = GlobalData.url + "api/Event/UpdateRouteEnrollments";
$http({
method: 'POST',
url: path,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(tmp)
}).
success(function (data, status, headers, config) {
$scope.hide();
FeedStorage.save({ "id": data.TeamId, "Route": "0CE0F3C9-BB1E-4931-98F3-362DDE7BD406" });
$scope.setPlatform('team');
}).
error(function (data, status, headers, config) {
$scope.hide();
alert('An error occured:' + status);
});
I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});