No actions found on the controller that match the request
Sorry for the lame question. I have already read all similar questions and still cannot solve the problem.
I am getting "No action found on the controller that matches the request error when called from ajax:
$.ajax({
url: '/api/ToyEdit/Post/',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({toyId: 1, toy: 'asd'}),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data);
},
error: function (xhr) {
alert(xhr.statusText);
}
})
Controller:
public class ToyEditController : ApiController
{
[System.Web.Mvc.HttpGet]
public EditToyViewModel Get(int? toyId)
{
var model = new EditToyViewModel();
if (toyId.HasValue)
{
model.Toy = Data.GetToy(toyId.Value);
}
model.Companies = Data.GetCompanies().ToList();
return model;
}
[System.Web.Mvc.HttpPost]
[System.Web.Mvc.ActionName("Post")]
public ActionResult Post(int? toyId, string toy)
{
var a = toy;
/*new Task<int>(() => DB.Context.Toys.FirstAsync().Id);*/
return new EmptyResult();
}
}
Routing:
routes.MapRoute(
name: "WebApi",
url: "api/{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What's wrong with the code?
UPDATE 1:
OK, it works when I use the following code:
public class Toy
{
public int? toyId {get; set;}
public string toy {get; set;}
}
[System.Web.Mvc.HttpPost]
[System.Web.Mvc.ActionName("Post")]
public ActionResult Post(Toy toy)
{
// your necessary codes
}
But how do you pass multiple primitive vars?
+3
source to share
1 answer
Try this: First create a class Toy
public class Toy
{
public int? toyId {get; set;}
public string toy {get; set;}
}
Then use it like next ...
[System.Web.Mvc.HttpPost]
[System.Web.Mvc.ActionName("Post")]
public ActionResult Post(Toy toy)
{
// your necessary codes
}
you can look here for more info ...
+2
source to share