在与该请求匹配的控制器上未找到任何操作

时间:2015-06-14 16:40:02

标签: c# asp.net ajax asp.net-mvc routing

抱歉这个蹩脚的问题。我已经阅读了所有类似的问题,仍然无法解决我的问题。

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

控制器:

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

路由:

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

代码有什么问题?

更新1:

好的,当我使用下一个代码时它会起作用:

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
}

但是如何传递一些原始的变量?

1 个答案:

答案 0 :(得分:2)

请尝试以下操作: 首先,创建Toy

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
}

您可以查看here了解更多信息......