Web Api: PUT/ POST method does not work - asp.net-mvc-3

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);
}

Related

Ajax post zero to controller

I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.

HttpPostedFileBase null on controller / ajax resquest

I'm trying to upload a file and send it to controller, but it's always returning null. Here's the code:
[HttpPost, ValidateAntiForgeryToken]
public JsonResult Edita(string nome, string login, string email, string dataNascimento, HttpPostedFileBase avatar)
{
if (ModelState.IsValid)
{
......
}
}
Here's the javascript code.... am i missing anything? I've tried with formData as well, but couldn't make it work
$(document).ready(function () {
$("#btnSalvar").click(() => {
if (form.valid()) {
var url = "#Url.Action("Edita", "Usuario")";
let myFormData = $("#formUsuario").serializeArray();
$.ajax(
{
type: "POST",
url: url,
data: myFormData,
dataType: 'json',
autoUpload: true,
success: function (data) {
if (data.status == "OK") {
$("#userModal").modal("hide");
}
}
});
}
});
});
I found out the solution for this issue. My had the #Html.AntiForgeryToken() validation, so i removed it and it worked!

OnDelete Handler always trigger a bad request

Trying to be more consistent with HTTP verbs, I'm trying to call a delete Handler on a Razor Page via AJAX;
Here's my AJAX code, followed by the C# code on my page :
return new Promise(function (resolve: any, reject: any) {
let ajaxConfig: JQuery.UrlAjaxSettings =
{
type: "DELETE",
url: url,
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json",
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
});
my handler on my cshtml page :
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
which never reaches ... getting a bad request instead !
When I switch to a 'GET' - both the type of the ajax request and the name of my handler function ( OnGetSupprimerEntite ) - it does work like a charm.
Any ideas ? Thanks !
Short answer: The 400 bad request indicates the request doesn't fulfill the server side's needs.
Firstly, your server is expecting a form by;
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
However, you're sending the payload in application/json format.
Secondly, when you sending a form data, don't forget to add a csrf token:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<script>
function deleteSupprimerEntite(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: myData ,
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
__RequestVerificationToken: "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
};
deleteSupprimerEntite(myData);
});
</script>
A Working Demo:
Finally, in case you want to send in json format, you could change the server side Handler to:
public class MyModel {
public int idEntite {get;set;}
public string infoCmpl{get;set;}
}
public IActionResult OnDeleteSupprimerEntite([FromBody]MyModel xmodel)
{
return new JsonResult(xmodel);
}
And the js code should be :
function deleteSupprimerEntiteInJson(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: JSON.stringify(myData) ,
contentType:"application/json",
headers:{
"RequestVerificationToken": "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
},
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
};
deleteSupprimerEntiteInJson(myData);
});

How to pass Ajax Json object to the Controller Class in .Net Core?

We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.
Can anyone here please advise the changes or the alternatives to achieve this?
View (Ajax Request)
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
GetEventDetails('#Url.Content("~/")');
});
function GetEventDetails(contextRoot) {
$.ajax({
type: "GET",
url: contextRoot + "api/EventsAPI",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
contentType: "application/json";
//Send data to controller ???
console.log(data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
}
Controller.cs
public ActionResult Index()
{
/*Do all stuff before returning view
1. Get Json Data from Ajax request
2. Deserialize the obtained Json Data
3. return to view
*/
return View("Index");
}
Update:
I have tried the solution given by #J. Doe, but still unable to get the result set. Please check the screenshot and below code..
Ajax Request:
function GetEventDetails(contextRoot) {
$.ajax({
type: "GET",
url: contextRoot + "api/EventsAPI",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
contentType: "application/json; charset=utf-8";
console.log(data);
var EventJson = data;
console.log(EventJson);
$.ajax({
type: "POST",
url: "#Url.Action("Index")",
dataType: "json",
data: EventJson,
contentType: "application/json; charset=utf-8",
//data: EventJson,
success: function (data) {
alert(data.responseText);
console.log('Data received: ');
console.log(data.responseText);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Class Properties:
public class RootObject
{
public Embedded _embedded { get; set; }
public Links _links { get; set; }
public Page page { get; set; }
}
Here is Action Result Controller:
public ActionResult Index(RootObject model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
//return View("Index");
}
Error Snapshot:
enter image description here
1) Add [FromBody] the controller you are returning to. This will make the controller expect a JSON object.
[HttpPost]
public ActionResult Index([FromBody]RootObject model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
//return View("Index");
}
2) If this doesn't work you are not posting a correct json object/you are not posting a json object use console.dir(EventJson); to inspect the object you are passing in the console of the browser.
3) How to create a JSON object in JS: https://www.w3schools.com/js/js_json_stringify.asp
We are trying
Hello soviet sojuz!
But back to question - A 2 months ago i created sample on GitHub with ajax with .Net Core - https://github.com/CShepartd/ASP.Net_Core_-_Ajax_Example
In short:
Make action with objects in controller:
public IActionResult Ajax(string name1, string name2)
{
return View();
}
Next in view send name1 and name2 to action
$('form').submit(function(event) {
event.preventDefault();
var data = {
name1: $("input[name='name1']", this).val(),
name2: $("input[name='name2']",this).val()
};
$.ajax({
type: 'POST',
url: '/Home/Ajax',
dataType: 'json',
data: data,
success: function(response) {
alert(response);
console.log('Data received: ');
console.log(response);
},
failure: function(response) {
//...
},
error: function(response) {
//...
}
});
});

Pass action with model to jquery ajax success call

My Jquery Ajax Call. How to return model from action to ajax and pass to another action.
function ChangeName(id)
{
var name=$("#name").val();
$.ajax({
cache:false,
url: "#Url.Action("EditName", "Order")",
data: "Name=" +name+"&Id="+id ,
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=model})
},JsonRequestBehavior.AllowGet);
}
public ActionResult Test(ProdModel model)//Model null
{
return RedirectToAction("List", "Product");
}
I have tried this but not getting success.
Try this
function ChangeName(id)
{
var name=$("#name").val();
var params = {
Name: name,
Id: id
};
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
window.location.href=data.Url;//doesnt work passes null model
}
});
}
[HttpPost]
public ActionResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(new
{
Url = Url.Action("Test","Order",new{model=product})
},JsonRequestBehavior.AllowGet);
}
Try as follows
In Edit Action try returning the model instead of url,
public josnResult EditName(string name,int id)
{
var product= GetProduct(id);
product.Name=name;
UpdateProduct(product);
var model=new ProdModel(){id=id};
return Json(model,JsonRequestBehavior.AllowGet);
}
Then in ajax Success call you can make another call to Test Action
$.ajax({
cache:false,
url: '#Url.Action("EditName", "Order")',
data: JSON.stringify(params),
type: "POST",
success: function (data) {
CallTestAction(data);
}
});
var CallTestAction = function(data) {
$.ajax({
cache:false,
url: '#Url.Action("Test", "Order")',
data: {model = data},
type: "POST",
success: function (data) {
}
});
};

Resources