asp.net mvc 4 - Calling action method for different entity in controller web api -
i have mvc 4 application. migrating of logic use web api. cannot make changestate
method work in following code ( 404 file not found). saw post:
and thinking of making different controller states different entity, curious how make work situation.
public class franchisecontroller : apicontroller { [datacontext] public ienumerable<franchiseinfoviewmodel> getallfranchises() { var allfranchises = new list<franchiseinfoviewmodel>(); var franchiseinfolist = _franchiseservice.getall(); foreach (var franchiseinfo in franchiseinfolist) { allfranchises.add(new franchiseinfoviewmodel(franchiseinfo, p => p.isimportant)); } return allfranchises; } [datacontext] [system.web.http.httppost] public string changestate(int franchiseid, franchiseproductionstates state) { _franchiseservice.changeproductionstate(franchiseid, state); var redirecttourl = "list"; return redirecttourl; } [datacontext] public franchiseinfoviewmodel getfranchise(int? franchiseid) { var realid = franchiseid ?? default(int); var franchiseinfo = _franchiseservice.createorget(realid); var franchiseinfoviewmodel = new franchiseinfoviewmodel(franchiseinfo, p => true); return franchiseinfoviewmodel; } }
here routes:
config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional }, constraints: new { id = @"\d*" } ); config.routes.maphttproute( name: "defaultapiplusactionandfolderid", routetemplate: "api/{controller}/{action}/{franchiseid}/{state}", defaults: null, constraints: new { action = @"[a-za-z]+", franchiseid = @"\d+", state = @"[a-za-z]+" } );
and js code calling action method:
var changestate = function (franchiseid, state) { var deferred = $.deferred(); amplify.request({ resourceid: 'changestate', success: deferred.resolve, error: deferred.reject, data: { franchiseid: franchiseid, state: state } }); return deferred; }; amplify.request.define('changestate', 'ajax', { url: "/api/franchise/changestate", type: "post", datatype: 'json', decoder: errorsdecoder });
note:
franchiseproductionstates
of type enum. suggestions welcome. first experience web api. thanks!
i able make work:
here how action method should like:
[httpput] public string changestate(int id, [frombody]franchiseproductionstates state) { _franchiseservice.changeproductionstate(id, state); var redirecttourl = "list"; return redirecttourl; }
note added [frombody] attribute. in fact put verb, not post.
this route:
config.routes.maphttproute( name: "test", routetemplate: "api/{controller}/{action}/{id}", defaults: new { id = routeparameter.optional } );
and how ajax call should done:
amplify.request.define('changestate', 'ajax', { url: "/api/franchise/changestate/3", type: "post", //datatype: 'json', contenttype: 'application/json; charset=utf-8', decoder: errorsdecoder });
for simplicity have hardcoded id parameter added url.
thanks!
Comments
Post a Comment