user1640256
user1640256

Reputation: 1719

Only first POST method of controller is called

I have a couple of post methods in my controller. Whenever I post data to this controller, only the first POST method is called. My requirement is to call the second method as the parameters are going to be different for both the methods. Here is the route config:

config.Routes.MapHttpRoute(
name: "AddUser",
routeTemplate: "api/users/adduser",
defaults: new { controller = "users" }
);
config.Routes.MapHttpRoute(
name: "ChangeUser",
routeTemplate: "api/users/changeuser",
defaults: new { controller = "users" }
);

This is my controller's code:

[AllowAnonymous]
[ActionName("adduser")]
public string PostDetails(JObject userData)//Always this method is called.
{
//My code here
}

[AllowAnonymous]
[ActionName("changeuser")]
public string ChangeUser(int userId)
{
//My code here
}

This is called from the view:

Ext.Ajax.request( { url: 'localhost/myapp/api/users/changeuser'
                  , mode: 'POST'
                  , params: { userID: 1 }
                  }
                );

Upvotes: 0

Views: 203

Answers (2)

petchirajan
petchirajan

Reputation: 4362

Adding constrains in the route config will solve your problem. Try below config..

config.Routes.MapHttpRoute(
name: "AddUser",
routeTemplate: "api/{controller}/{action}",
defaults: new { },
constraints: new { controller = "users", action = "adduser" }
);

config.Routes.MapHttpRoute(
name: "ChangeUser",
routeTemplate: "api/{controller}/{action}",
defaults: new { },
constraints: new { controller = "users", action = "changeuser" }
);

The C# part:

[AllowAnonymous]
[ActionName("adduser")]
[AcceptVerbs("Post")]
public string PostDetails(JObject userData)//Always this method is called.
{
//My code here
}

[AllowAnonymous]
[ActionName("changeuser")]
[AcceptVerbs("Post")]
public string ChangeUser(int userId)
{
//My code here
}

Upvotes: 1

Maratto
Maratto

Reputation: 162

Try:

[HttpPost, ActionName("Name")] 

instead of:

[ActionName("Name")]

I'm not an expert but it might work this way.

Upvotes: 0

Related Questions