WebApi 2 - Json request pending - c#

when I call one webapi from ajax, if I return something different from simple string or int, the request is still pending.
here my javascript:
var endPoint = "/api/services/attivita/set";
$.ajax({
url: endPoint,
data: JSON.stringify(
{
'id': attivita.IDTipoAttivita,
'descrizione': $('#Descrizione').val()
}
),
dataType: 'json',
contentType: "application/json;charset=utf-8",
processData: false,
type: 'post',
success: function (data) {
console.log('ok');
},
error: function (data) {
console.log('ko');
}
});
and here webapi code
[System.Web.Http.HttpGet]
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/services/attivita/set")]
public TipoAttivita SetAttivita([FromBody] dynamic obj)
{
var id = (int)obj.id;
var descrizione = obj.descrizione.ToString();
var nuovo = id == -1;
var attivita = new TipoAttivita()
//do stuff of attivita object
this.CurrentDb.TipoAttivita.Add(attivita);
this.CurrentDb.SaveChanges();
return (attivita);
}
If I change to "public int...." and "return(1);" at the end of the function everything works fine.
in WebApiConfig.cs I have this
var jsonFormatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}
};
jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Clear();
config.Formatters.Add(jsonFormatter);
Any idea?
Thanks a lot

Try to change return type to IHttpActionResult and return Ok(attivita)

Related

Internal Server Error when calling ajax post method

I'm facing problem with calling ajax POST method, it just returns error with message: Internal Server Error.
My script looks like this:
$('.add-column').click(function () {
var ids = [];
$('#table1 > tbody > tr.selected').each(function () {
var ident = $(this).attr('id');
ids.push(ident);
});
$.ajax({
url: '/Syzyf/AddUserColumns',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { id : JSON.stringify(ids) },
cache: false,
success: function (result) {
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
And controller's method:
[HttpPost]
public ActionResult AddUserColumns(List<int> ids)
{
var userId = GetUserId(User.Identity.Name);
using (var ctx = new SyzyfContext())
{
foreach (var id in ids)
{
var uc = new UserColumns();
uc.ColumnId = id;
uc.UserId = userId;
ctx.UserColumns.Add(uc);
}
ctx.SaveChanges();
}
return Json("Success");
}
I thought that it may be problem with data, but when I've changed method to call ajax function foreach id in ids, It returned same error. What do I do wrong ?
EDIT
I've found solution.
The problem was with Database Table, it did not have PRIMARY KEY...

How to send data object which contain upload files and string to controller using ajax?

I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}

How to send multiple data in single FormData object in Ajax?

My application has multiple data like Text-box value, label value, Drop-Down value,File Data and send same data at server side and store in database
To achieve this, i have used below method but now i want to use Formdata and append each value and send it to server side
How to achieve this scenario using Formdata with specific object type.
Below is the code
var selectedText = $('#Commentinput').text();
$('#actioncomments').text(selectedText);
var debitEntityValue = $('#DrAccount option:selected').text();
var creditEntityValue = $('#CrAccount option:selected').text();
var amount = $("#Amountinput").val();
var paymentActionReason = $('#action').text();
var paymentCommentReason = $('#Commentinput').val();
var prepayAccountId =#Model.prepaidBranchList.PrepaidID;
var transactionDate = '#DateTime.Today';
var transactionExtensions = "1";
var fileBase64Data = $("#fileUpload").text();
if ($('#Commentinput').val() == "") {
paymentCommentReason = "No Comment";
}
else {
paymentCommentReason = $('#Commentinput').val();
}
var adjustmentTransactioninfo =
{
PaymentReasonMasterId: paymentReasonMasterId,
DebitEntityValue: debitEntityValue,
CreditEntityValue: creditEntityValue,
Amount: amount,
PaymentActionReason: paymentActionReason,
PaymentCommentReason: paymentCommentReason,
PrepayAccountId: prepayAccountId,
TransactionDate: transactionDate,
TransactionExtensions: transactionExtensions
};
var data = JSON.stringify({
'adjustmentTransactioninfo': adjustmentTransactioninfo,
'fileData': 0
});
var url = "#Html.Raw(Url.Action("AdjustmentTransaction",
"PrepaidActivity"))";
url += '?branchCode=' + '#Model.prepaidBranchList.IASBranchCode'
$.ajax({
url: url,
traditional: true,
data: data,
enctype:"multipart/form-data",
contentType: "application/json charset=utf-8",
dataType: "json",
type: 'POST',
success: function (data) {
$("#ajaxLoader").show();
if (data != null) {
var ProductActionID = data.SuccessMessage.split(':');
uploadFile.append('ProductActionID' , ProductActionID[1]);
FileUpload(uploadFile);
var dialog = document.querySelector('#Finaldialog');
var ConfirmationScreen = $("<p></p>").text(data.SuccessMessage);
$("#finalmdl-dialog").append(ConfirmationScreen);
dialog.showModal();
dialog.querySelector('button:not([disabled])').addEventListener('click', function() {
dialog.close();
location.reload();
});
}
}
});`
Controller code
public JsonResult AdjustmentTransaction(TraxAdjustmentTransactionInfo adjustmentTransactioninfo, string fileData, string branchCode)
{
PrepaidAdminService.PrepaidAdminDashBoardServiceClient _PrepaidAdminService = new PrepaidAdminService.PrepaidAdminDashBoardServiceClient();
TraxAdjustmentTransactionResult result;
adjustmentTransactioninfo.ProductActionMasterId = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["ProductActionMasterId"]);
adjustmentTransactioninfo.ProductCode = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ProductCode"]);
adjustmentTransactioninfo.DebitEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.CreditEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.UserId = Utility.UserID;
adjustmentTransactioninfo.RetailerId = _PrepaidAdminService.GetBranchRetailerId(branchCode);
use serializeArray and can be add the additional data:
var data = $('form').serializeArray();
data.push({name: 'Amit', value: 'love'});
$.ajax({
type: "POST",
url: "url",
data: data,
success: function(data) {
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
Remove the #Html.Raw(Url.Action()), contentType and JSON.stringify() and leave that to the ModelBinder. Change your ajax to this:
$.ajax({
url: '#Url.Action("AdjustmentTransaction", "PrepaidActivity")',
traditional: true,
data: {
adjustmentTransactioninfo: adjustmentTransactioninfo,
fileData: "0",
branchCode: '#Model.prepaidBranchList.IASBranchCode'
},
enctype: "multipart/form-data",
type: 'POST',
success: function (data) {
alert("success");
}
});
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
// Param1 and param2 name should be same as method argument

Receive FormData as a single Key - Asp.NET MVC

I have a Patient like this in AngularJS
var Patient = {
PatientID : $scope.PatientID,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
Angular Controller
var pData = new FormData();
pData.append("model", Patient);
var getData = angularService.AddPatient(pData);
Angular Service
this.AddPatient = function (patientData) {
var response = $http({
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
method: "post",
url: "/Student/AddPatient",
data: patientData,
dataType: "json"
});
return response;
}
And my Method in MVC Controller
public String AddPatient() {
var model = Request.Form["model"];
// this giving me an object instead of JSON String
}
Please help me, how do i receive that Patient data, Read and save it in the database, and i dont want to use any loop, i mean like this
// I dont want to do this
var patientData = new FormData();
angular.forEach(Patient, function (value, key) {
patientData.append(key, value);
});

JQuery Ajax to send Sortable Array in C#

I'm picking up items from a ul, and turning into an array. My controller is below and the variable items is getting empty​​.
What should I do to the controller receiving the correct value.
Controller:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GravarConfiguracao(string[] itens)
{
var indicaores = itens;
var sequencia = 1;
foreach (var item in indicaores)
{
var atualizaIndicador = IndicadoresDoUsuario.AtualizarSequencia(Usuario.Codigo, Convert.ToInt32(item), sequencia);
sequencia++;
}
return Json(new { HttpStatusCode.OK });
}
JQuery:
$.ajax({
type: 'GET',
url: makeUrl("Indicador/GravarConfiguracao"),
data: JSON.stringify({ itens: $("#sort1").sortable('toArray') }),
dataType: 'json',
contentType: 'application/json',
success: function (dados) {
},
error: function (err) {
alert("Erro: - " + err);
}
});
JQuery send:
Query String Parameters:
{"itens":["itemIndicador_3","itemIndicador_10","itemIndicador_11"]}:

Categories

Resources