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>
Related
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; }
}
my model:
public class Hello
{
public List<string> name;
public List<string> phone;
public List<string> contact;
}
my controller code is
public ActionResult Home(Hello obj) // obj is coming out to be null
{
}
my script is
var names =[];
var phones =[];
var contacts = [];
// some code to fill the arrays
var obj = [{
name: names,
phone: phones,
contact: contacts,
}];
debugger;
$.ajax({
cache: false,
url: 'Home',
data: { obj:obj },
success: function (data) {
var response = JSON.parse(data);
window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
i can see in the debugger that data is stored in the arrays but when i am sending data to controller the obj is null can someone suggests where am i going wrong ?
You have object in code behind so do not pass array of Hello object.
And also use POST request because GET request have not message body.
Please use below
var obj = {
name: ['1', '2', '3'],
phone: ['234324', '34343243', '3434234234'],
contact: ['Test1', 'Test2', 'Test3']
};
debugger;
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Home',
data:JSON.stringify({ obj: obj }),
success: function (data) {
var response = JSON.parse(data);
// window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
public class Hello
{
public List<string> name { get; set; }
public List<string> phone { get; set; }
public List<string> contact { get; set; }
}
Actually i solved the problem , i had to set
traditional:true,
in my ajax call
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
Here is my controller;
public class ProductionStateController : ApiController
{
private readonly IFranchiseService _franchiseService;
public ProductionStateController(IFranchiseService franchiseService)
{
_franchiseService = franchiseService;
}
[DataContext]
public string PutProductionState(int id, FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(id, state);
var redirectToUrl = "List";
return redirectToUrl;
}
}
My ajax call;
self.selectState = function (value) {
$.ajax({
url: "/api/ProductionState",
type: 'PUT',
contentType: 'application/json',
data: "id=3&state=Pending",
success: function (data) {
alert('Load was performed.');
}
});
};
My route;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I am getting a 404 File not found error.
Same if I replace the method to be POST.
If I make it GET everyting works.
I am missing something here. Any help will be greatly appreciated.
The web api framework matches action methods which start with the http verb. So PutProductionState is ok as a name.
I was able to make this work. The problems are the following: the second parameter of the action method should be marked with the [FromBody] attribute:
public string PutProductionState(int id, [FromBody] FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(id, state);
var redirectToUrl = "List";
return redirectToUrl;
}
And the ajax call should look like this:
self.selectState = function (value) {
$.ajax({
url: "/api/ProductionState/3",
type: 'PUT',
contentType: 'application/json',
data: "'Pending'",
success: function (data) {
alert('Load was performed.');
}
});
};
Note the id parameter added to the url and the stringified data.
Thanks!
<script>
function CallData(ids) {
debugger;
if (ids != null) {
$.ajax({
url: "EVENT To Call (Which is in Controller)",
data: {
SelId: $("#Control").val()
},
dataType: "json",
type: "POST",
error: function () {
alert("Somehitng went wrong..");
},
success: function (data) {
if (data == "") {
//Do Your tuff
}
}
});
}
}
//In Controller
[HttpPost]
public ActionResult EVENT To Call (Which is in Controller) (int ids)
{
//Do Your Stuff
return Json(Your Object, JsonRequestBehavior.AllowGet);
}
on MVC3 Page load i have a String in a Model which is should be the JSONObj.
private string CreateJSONObj(Model model)
{ return "{ name: 'test', Items: [{ test: 1 }, { test: 2 }]"; }
Model.jsonModel = CreateJSONObj(model);
Now i want to implement it in my page:
<script>var jsModel = eval('#Model.jsonModel');
var jsonModel = $.toJSON(jsModel);
$.ajax({
url: 'Page/SetJSON/',
type: "POST",
data: jsonModel,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$('#test').html('Saved').fadeIn(),
},
error: function () {
$("#test").html("error"),
}
});</script>
But the Controller gets a null Object. If i write the jsonstring into the script everthing is fine.
Should i use eval? But var jsModel = eval('#Model.jsonModel'); has no effect. What is wrong? :-)
You don't need to use a CreateJSONObj method or a jsonModel property on your model. In order to use it in the view you could simply use the JavaScriptSerializer class which will convert the server side model object into a javascript object:
<script type="text/javascript">
var jsModel = #Html.Raw(new JavaScriptSerializer().Serialize(Model));
$.ajax({
url: '#Url.Action("SetJSON", "Page")',
type: 'POST',
data: JSON.stringify(jsModel),
contentType: 'application/json; charset=utf-8',
success: function () {
$('#test').html('Saved').fadeIn();
},
error: function () {
$('#test').html('error');
}
});
</script>
This will successfully send the model to the following controller action:
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
where the Model class contains all the necessary information:
public class Model
{
public string Name { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public int Test { get; set; }
}
and the controller:
public class PageController: Controller
{
// Used to render the view
public class Index()
{
var model = new Model
{
Name = "Test",
Items = new[]
{
new Item { Test = 1 },
new Item { Test = 2 },
}
};
return View(model);
}
// Used to handle the AJAX POST request
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
}