views:

45

answers:

1

I am new to MVC and I am wondering how to do the following; Using a foreach loop and a user control I am happily displaying a list of users from a database. This page is an admin page, and the associated permissions for each user are displayed. I want to change this so that under each heading for each role there is a checkbox that determines whether that role is allocated to that person. When the admin clicks on a checkbox, the role for that user changes accordingly. Ideally the update should take place straight away on the database.

What is the best way to do this in MVC2?

+2  A: 

If your intention is to have the values changed and triggered by the toggle of the checkbox, consider these suggestions.

Use jQuery to attach an event for each of your checkboxes. Have it make an AJAX call to a URL in your controller. That event will fire whenever toggled, and would run this code:

$.ajax({
//this could also be built with '<%= Url.Action("UpdateUserRole","User") %>/
url: "/User/UpdateUserRole", 
type: "POST",
data: {
       "userID" :  "", //somehow place the user's ID here - cookie, session, etc.
       "roleID" : $('#theCheckbox').val(),
      },
success: function(data) { alert(data); }
});

Make that new controller action method. Perhaps it looks like:

public string UpdateUserRole(int userID, int roleID){
    //go update the DB with the 2 params as needed.
}

Within, you can call your database to remove/add the role to the user, depending on whether it exists currently. It's up to you whether you want a boolean to indicate enable/disable, but that'll complicate your View. My suggestion would make the action a simple 'flip' of the state in the database. If the user/role pairing exists, delete it. If it doesn't, create it.

Ensure security of that controller method. You may not want anyone to detect how the scheme works. Perhaps include Html.AntiForgeryToken in your form, and require it on your controller method.

p.campbell
I have put in a click event and I have put in an AJAX post. I just need the userId of the update. However I think there is a mistake in the code here; <script type="text/javascript"> function TestClickFunc(userId) { //alert(userId); $.ajax({ url: "/Users/UpdateEmailDistributionListFlag", type: "POST", data: { "userId" : userId }, success: function(data) { alert(data); } }); }
arame3333
This fails to call the following method in the UsersController; public void UpdateEmailDistributionListFlag(int userId) { // db update }
arame3333
@arame3333: see the update to use Url.Action to build the URL to your controller
p.campbell