Calling a WebAPI from client side through POST method fails - ajax

We are trying to call a web-api from client side. The web api contains a Request class with Amount as decimal. We are trying to pass a decimal amount and getting back the same amount in response from webapi along with the status.
The problem is that the web-api is not able to receive the amount. When we try to attach with webapi we see only null in the Amount field in the Request class.
Any help in this regard would be great.
Below is how we call from client side
var requestMessage = { RequestSale: { Amount: '100.545M' } };
var request = {
type: "POST",
contentType: "application/json;charset=utf-8",
datatype: "json",
url: "http://<machinename>/Demo/api/monthlySales/InsertMonthlySales",
successCallback: successCallback,
errorCallback: errorCallback,
filterCriteria: null,
data: JSON.stringify(requestMessage)
//header: { key: "Accept", value: "application/json" },
};
utilityTest.getData(request);
expect(true, true);
utilityTest.getData(request) -- This makes the actual call, below is code
utilityTest.getData = function (request) {
$.ajax({
type: request.type,
contentType: request.contentType,
datatype: request.datatype,
url: request.url,
data: request.data,
cache : false,
beforeSend: function (xmlHttpRequest) {
if (request.header) {
xmlHttpRequest.setRequestHeader(request.header.key, request.header.value);
}
},
success: function (data, textStatus, xmlHttpRequest) {
if (request.successCallback) {
request.successCallback(data, request.filterCriteria);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
if (request.errorCallback)
request.errorCallback(xmlHttpRequest, textStatus, errorThrown);
} });
}
Web-api method
[HttpPost]
public ResponseSale InsertMonthlySales(RequestSale sale)
{
var curMonth = DateTime.UtcNow.Month;
var salesAmount = Convert.ToDecimal(sale.Amount);
ResponseSale response = new ResponseSale();
response.Amount = salesAmount;
response.Id = curMonth;
if (monthlySales.ContainsKey(curMonth))
{
monthlySales[curMonth] += salesAmount;
}
else
{
monthlySales.Add(curMonth, salesAmount);
}
response.Status = "InsertMonthlySales";
return response;
}
Request/Response contract for web-api
namespace DemoContracts.Object
{
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://DemoSchema.ContractSale")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://DemoSchema.ContractSale", IsNullable = false)]
public class RequestSale {
public decimal Amount { get; set; }
}
}
namespace DemoContracts.Object
{
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://DemoSchema.ContractSale")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://DemoSchema.ContractSale", IsNullable = false)]
public class ResponseSale
{
public string Status { get; set; }
public decimal Amount { get; set; }
public int Id { get; set; }
}
}
--JSON as captured from IE
Request Body :
{"RequestSale":{"Amount":100.545}}
Response Body
{"Status":"InsertMonthlySales","Amount":0.0,"Id":9}
In Web API, InsertMonthSales request object RequestSale.Amount is always be 0. We are not getting the passed 100.545 value

Related

value is not pass from view to controller using ajax

I am performing an AJAX call using a function but my value did not pass through it.
function GoToUpdatePage(currentID) {
var SessionTegInfo = {};
SessionTegInfo.StockCode = document.getElementById("stocktxt").checked;
SessionTegInfo.StockCodeValue = document.getElementById("SearchValuestock").value;
SessionTegInfo.CurrentID = currentID;
$.ajax({
url: "#Url.Action("UpdateWithSessionStore", "MyMasterUpdate")",
data: JSON.stringify(SessionTegInfo),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (data) {
}
});
}
Here is my code from server side
[HttpPost]
public IActionResult UpdateWithSessionStore([FromBody] MySessionClass SessionTegInfo)
{
.....
return RedirectToAction("Index", "MyUpdateController", new { id = SessionTegInfo.CurrentID });
}
Here are my class details
public class MySessionClass
{
public string StockCode { get; set; }
public string StockCodeValue { get; set; }
public string CurrentID { get; set; }
}

How to pass dictionary item from client side (Ajax) to server side (MVC API)

I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.
function FileSenderAPI(){
var DictionaryData = new Object;
DictionaryData = document.getElementById("hidFilePath").value;
var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
$.ajax({
url: Url,
method: 'Get',
data Type: "json",
data: {
ModelsPath:JSON.stringify(DictionaryData),
Exchange: exchange,
Exchange_key: key,
},
success: function (data, textStatus, xhr) {
alert(data);
},
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``
Here is a solution. You can try it. Hope to help, my friend :))
1) Create a model
public class DictionaryModel
{
public Dictionary<string, string> dict { get; set; }
public string Exchange { get; set; }
public string Exchange_Key { get; set; }
}
2) Action
[HttpPost]
public JsonResult Example(DictionaryModel model)
{
// Your Logic
return Json("Success");
}
3) In View
$('#btClick').on('click', function () {
var dict = {};
dict["id"] = "200";
dict["Name"] = "Chris";
dict["DynamicItem1"] = "Item 1";
var theObject = {};
theObject.dict = dict;
theObject.Exchange = "Abc";
theObject.Exchange_Key = "123";
let url = '#Url.Action("Example","Home")';
$.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
console.log("success");
}, "json");
});

send complex and simple parameter to web api using ajax

i write web api.
web api controller:
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
{
...
}
}
and ajax:
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"xx":'admin',"yy":'123',"task": JSON.stringify(task) },
type: 'Post',
success: function (data) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
and WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
when run ajax, return error:
No action was found on the controller 'TaskApi' that matches the request
Always feed the POST methods with class type parameters. Please do the following modification on the API and JavaScript.
1. Create a model class
<pre>
public class Model
{
public string xx { get; set; }
public string yy { get; set; }
public CommonTask Task { get; set; }
}
</pre>
Then modify your Web API to accept a type of your class model
<pre>
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask([FromBody] Model model)
{
}
}
</pre>
Change your ajax method to pass a json object similar to the Model class
<pre>
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var data = {
"xx": 'admin',
"yy": '123',
"task" : JSON.stringify(task)
};
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"model": JSON.stringify(data) },
type: 'Post',
success: function (message) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
</pre>

Not getting Json object (having a collection) correctly in controller using ajax call

I am sending a json object to controller via ajax call, data property of ajax call showing correct data. On post to controller's method -received parameter having collection and its count is showing perfectly but the properties inside the collection is not showing values.
Here is the code -
Controller-
[HttpPost]
public ActionResult ImageOperations(ImageProcessingModel imageProcessingModel)
{
return Json("sucess");
}
Model-
public class ImageProcessingModel
{
public string Source { get; set; }
private List<ThumbnailImageSubTaskModel> _thumbnailImageSubTaskModel;
public List<ThumbnailImageSubTaskModel> ThumbnailImageSubTaskModel
{
get
{
if (_thumbnailImageSubTaskModel == null)
{
_thumbnailImageSubTaskModel = new List<ThumbnailImageSubTaskModel>();
}
return _thumbnailImageSubTaskModel;
}
}
}
js-
var ImageProcessingModel =
{
"Source": "test",
"ThumbnailImageSubTaskModel":allThumbnails.allItems()
}
allThumnails.allItems is ko.observableArray() which having values.
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});
here ImageProcessingModel having all values and source is simple a string so this value is coming in the controller only the ThumbnailImageSubTaskModel showing counts but not its value.
Thanks!!
A common problem encoutered with sending JSON through AJAX to MVC. Many forget to set the type of data in their AJAX request.
Try setting the datatype and contentType:
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
**contentType: 'application/json; charset=UTF-8',
dataType: 'json',**
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});

why postify works and stringify doesn't?

In server side I have following class
public class EditorContext
{
public Module Module { get; set; }
public Holder Holder { get; set; }
}
public class Module
{
public string CodeName { get; set; }
public string Content { get; set; }
}
public class Holder
{
public int Id { get; set; }
public int Type { get; set; }
}
public class EditorController : Controller
{
[HttpPost]
public ActionResult AddModule(EditorContext context)
{
return Json(new { });
}
}
From the client I send request like this
var data =
{
Module:
{
CodeName: 1,
Content: 2
},
Holder:
{
Type: 3,
Id: 4
}
};
$.ajax({
type: "POST",
url: 'Editor/AddModule',
data: JSON.stringify(data),
async: false,
success: function () {
},
error: function (xhr, status, error) {
throw new Error();
}
});
1 - Fiddler shows that he sent {"Module":{"CodeName":1,"Content":2},"Holder":{"Type":3,"Id":4}}, but in server Request.Form = %7b%22Module%22%3a%7b%22CodeName%22%3a1%2c%22Content%22%3a2%7d%2c%22Holder%22%3a%7b%22Type%22%3a3%2c%22Id%22%3a4%7d%7d, WHY?
2 - If instead of "JSON.stringify(data)" I use "postify" like in here, so EditorController.AddModule gets already filled EditorContext. This postify change the data to "Model.CodeName=1&Model.Content=2&Holder.Type=3&Holder.Id=4". So, why in this way EditorContext is filled automatically by default binder and in (1) it doesn't?
Thank you
You need to tell the binder that your data is JSON, otherwise it has no idea it should be parsing it as such. Add the correct content type header to your request:
$.ajax({
type: "POST",
url: 'Editor/AddModule',
data: JSON.stringify(data),
contentType: "application/json",
async: false,
success: function () {
},
error: function (xhr, status, error) {
throw new Error();
}
});

Resources