这是我的控制器;
public class ProductionStateController : ApiController
{
private readonly IFranchiseService _franchiseService;
public ProductionStateController(IFranchiseService franchiseService)
{
_franchiseService = franchiseService;
}
[DataContext]
public string PutProductionState(int id, FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(id, state);
var redirectToUrl = "List";
return redirectToUrl;
}
}
我的ajax电话;
self.selectState = function (value) {
$.ajax({
url: "/api/ProductionState",
type: 'PUT',
contentType: 'application/json',
data: "id=3&state=Pending",
success: function (data) {
alert('Load was performed.');
}
});
};
我的路线;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我收到404 File not found
错误。
如果我将方法替换为POST
,则相同。
如果我做到GET
每件都有效。
我在这里遗漏了一些东西。任何帮助将不胜感激。
答案 0 :(得分:1)
web api框架匹配以http动词开头的动作方法。所以PutProductionState
可以作为名称。
我能够做到这一点。问题如下:action方法的第二个参数应该用[FromBody]属性标记:
public string PutProductionState(int id, [FromBody] FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(id, state);
var redirectToUrl = "List";
return redirectToUrl;
}
ajax调用应该如下所示:
self.selectState = function (value) {
$.ajax({
url: "/api/ProductionState/3",
type: 'PUT',
contentType: 'application/json',
data: "'Pending'",
success: function (data) {
alert('Load was performed.');
}
});
};
请注意添加到网址的id参数和字符串化数据。
谢谢!
答案 1 :(得分:0)
<script>
function CallData(ids) {
debugger;
if (ids != null) {
$.ajax({
url: "EVENT To Call (Which is in Controller)",
data: {
SelId: $("#Control").val()
},
dataType: "json",
type: "POST",
error: function () {
alert("Somehitng went wrong..");
},
success: function (data) {
if (data == "") {
//Do Your tuff
}
}
});
}
}
//在控制器
中[HttpPost]
public ActionResult EVENT To Call (Which is in Controller) (int ids)
{
//Do Your Stuff
return Json(Your Object, JsonRequestBehavior.AllowGet);
}