【问题标题】:No action was found on the controller that matches the request在控制器上找不到与请求匹配的操作
【发布时间】:2015-08-30 03:59:04
【问题描述】:

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

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

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

【问题讨论】:

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


【解决方案1】:

尝试如下: 首先,创建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了解更多信息...

【讨论】:

  • 再说一次,这并不能解释为什么他会得到 404。
  • 实际上,在 web api 中,route.MapRoutes 通过 url 模式映射...例如:“{controller}/{action}/{id}”映射一个控制器的操作,其中包含一个名为id你可以看这里-asp.net/web-api/overview/web-api-routing-and-actions/…
  • 似乎当我使用你的代码时它可以工作。但是为什么我不能只传递两个原始变量?
  • @LbISS Web API 只能绑定来自 HTTP 主体的单个原始类型。这就是你困惑的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 2013-05-26
  • 2017-09-25
  • 2015-08-13
  • 2016-01-10
  • 2015-10-13
  • 1970-01-01
相关资源
最近更新 更多