views:

80

answers:

1

Hi, I am trying to update the Roles a specific group has in my application. The Group model I use in my view has an additional AllRoles IEnumerable attached to it, so that in my view I can do something like this:

<%: Html.ListBoxFor( model => model.aspnet_Roles, new MultiSelectList( Model.AllRoles, "RoleId", "RoleName" ), new { @class = "multiselect" } )%>

This generates a multiple select drop down as expected. However, coming form PHP, I noticed that the name of the select was without square brackets, maybe that is OK in ASP.NET but in PHP it is wrong. Now, how do I go about updating the group after submiting the form, more precisely, how can I read the multiselct selected values. What I need is that based on the RoleIds that I receive to Add respective aspnet_Roles to my Group model.

Trying to read the received values using HttpContext.Request.Form["aspnet_Roles"] failed and is also ugly. Can I somehow use the model to fetch the needed data? Controller function:

[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Edit( SYSGroups updatedGroup ) {}

Thanks

+1  A: 

The selected ids will be sent as a collection:

[HttpPost]
public ActionResult Edit(string[] aspnet_Roles) 
{
    // the aspnet_Roles array will contain the ids of the selected elements
    return View();
}

If the form contains other elements that need to be posted you could update your model:

public class SYSGroups
{
    public string[] Aspnet_Roles { get; set; }
    ... some other properties
}

and have your action method look like this:

[HttpPost]
public ActionResult Edit(SYSGroups updatedGroup) 
{
    // updatedGroup.Aspnet_Roles will contain an array of all the RoleIds
    // selected in the multiselect list.
    return View();
}
Darin Dimitrov
Can I avoid using another parameter to the Controller function? Can I use the received aspnet_Group to read the collection?public ActionResult Edit( SYSGroups updatedGroup ) {}
Interfector
Yes, add the `Aspnet_Roles` array property to the `SYSGroups` model class as I've shown. The property you are binding to in the `Html.ListBoxFor` needs to be an array like `Html.ListBoxFor(model => model.aspnet_Roles, ...` - `aspnet_Roles` needs to be a string array.
Darin Dimitrov
Just adding that parameter to the Controller function is OK, doesn't make sense to add weight to my model.Thx.
Interfector

related questions