Reputation: 22232
The scenario:
a User
class has several groups of properties: password
, address
, preference
, roles
.
We need different Ajax calls to update the (1) user password, (2) user profile, (3) roles a user is in.
All the tutorials and examples only shows one POST action to update the whole User class. My question is how we can update only part of the class.
For example, when updating the user password, we will:
One solution: (the easiest to think of)
GET
action with the userId to retrieve all the data for a userPOST
action with the updated data, which contains all properties in the User class.POST
action will update the whole data without knowing only the password is changed.The benefit: only one POST
action is needed for the ApiController
.
The shortcoming: we have to Ajax twice.
So, is it possible that we can have multiple POST
actions in one ApiController
? For example, PostPassword(userId, password)
, PostProfile(userId, profile)
and PostRoles(userId, roles)
.
In this way, we will only call PostPassword
to send the password to ApiController
. In client side, there will be only one Ajax call. It is on the server where we will do the update. The benefit is of course the reduced data transferred over Internet.
If it is possible, what is the correct way to direct all different POST
calls to their corresponding actions in the ApiController
?
Please help us. Thank you all.
Upvotes: 0
Views: 450
Reputation: 75316
Most of cases, needless to have muptile post actions, I think. The typical case is consumer needs to edit user. So, s/he needs to load user data first to show on the edit form. After editing, consumer can click Save button to submit data and call POST action on api controller.
If your case is different, you should have nullable property for value type, and then the logic which should be checked in controller is if any property is null, it should not update this property into database.
Upvotes: 2
Reputation: 150148
You can only have one post action per controller action name. That is, you cannot do
// NOT VALID:
public ActionResult UpdateUser(string newPassword) { }
public ActionResult UpdateUser(List<string> newRoles) { }
However, parameters of the action can certainly be nullable. If a given property is not supplied in a given HTTP request, the value of the property in the controller would be null.
// VALID:
public ActionResult UpdateUser(string newPassword, List<string> newRoles)
{
if (newPassword != null) { } // It must have been supplied
if (newRoles != null) { } // It must have been supplied
}
Alternatively, you can have related controller actions that each handle one of your use cases, e.g. UpdatePassword(...), UpdateAddress(...), ...
Upvotes: 1