LbISS
LbISS

Reputation: 630

No action was found on the controller that matches the request

Sorry for the lame question. I've already read all similar questions and still can't resolve my issue.

I'm getting 'No action was found on the controller that matches the request' error when calling 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 code?

UPDATE 1:

OK, it works when i'm using the next 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 to pass a few primitive vars?

Upvotes: 3

Views: 15065

Answers (1)

PaulShovan
PaulShovan

Reputation: 2134

Try as following: First, create Toy class

public class Toy
{
  public int? toyId {get; set;}
  public string toy {get; set;}
}

Then use it as following...

[System.Web.Mvc.HttpPost]
[System.Web.Mvc.ActionName("Post")]
public ActionResult Post(Toy toy)
{
    // your necessary codes
}

you can take a look here for more information...

Upvotes: 2

Related Questions