2015-06-14 73 views
3

对不起,这个跛脚的问题。我已经阅读过所有类似的问题,但仍无法解决我的问题。控制器上找不到与请求匹配的动作

我越来越从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 
} 

但如何通过一些基本的增值经销商:

OK,就当我使用下面的代码工作?

+0

您的maproute与操作不匹配 – gypsyCoder

+1

Web API只能绑定来自HTTP主体的单个基本类型 – gypsyCoder

+0

但在不同的文章,如http://www.codeproject.com/Articles/795483/Do-GET-POST-PUT-DELETE-in-asp-net-MVC-with-Jquery他们使用多个变量。他们都错了吗? – LbISS

回答

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更多信息...

+0

再一次,这并不能解释他为什么会得到404。 – FrankerZ

+0

实际上,在web api中'route.MapRoutes'通过url模式映射...例如:“{控制器}/{动作}/{标识符}“映射控制器的动作,其中包含一个名为'id'的参数 您可以在这里查看 - http://www.asp.net/web-api/overview/web -api-routing-and-actions/routing-in-aspnet-web-api – gypsyCoder

+0

看来,当我使用你的代码它的工作原理。但为什么我不能通过两个原始变量? – LbISS

相关问题