简体   繁体   中英

c# MVC: How to update user roles?

I have a viewmodel which exposes a few public virtual ICollection Roles { get; set; }

This is great for bringing back what roles a user belongs to.. But how do I update the roles of a user from a form.

For testing I've tried adding a hidden field called "Roles" and entered both "Admin" and it's GUID as it's value to send back to the server:

<input type="hidden" name="Roles" value="Admin" />
<input type="hidden" name="Roles" value="7feab829-b86c-4a94-90bf-f35e9ce04b01" />

Howwver, when passes to the server I can see that this way creates an invalid modelstate -- Any suggestions would be greatly appreciated!

In light of your comments, I see a few straightforward solutions. First, remove the hidden input fields. Those don't buy you anything and only hurt you when you go to validate the model

  1. Utilize drop down lists for roles and pass it back up on your model. The value should be the selection.
  2. Pass them up as strings and parse in the controller, as you mentioned
  3. Use radial options, each with a unique ID. Pass up the ID and correspond that ID to a value in your controller.

In the controller, you are absolutely correct. Get the role and call Roles.AddUserToRole().

I think you're already on the right track :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM