I'm sure what I want to do is possible, but I can't figure out how.
I have a view which shows some information about the selec开发者_开发知识库ted user, including their roles. I have added a dropdown to the view showing all the roles and want to have a button which will add the selected role from the dropdown to the current user. To allow this I have a controller with this method:
public ActionResult AddUserRole (string userName,string roleName)
{
if (Roles.IsUserInRole (userName,roleName)==false)
{
Roles.AddUserToRole (userName,roleName);
}
return RedirectToAction("Profile", "Profile",new {userName=userName});
}
but I can't figure out how I set the selected item in the dropdown from the view to be the string roleName
parameter in the controller method. I can set the userName easily enough as this is static. What am I missing? Here's my view, or at least the relevant bit:
<%
using (Html.BeginForm( "AddUserRole", "Account",new {userName=Model.UserName}))
{%>
<div id="AddRoleToUser">
<asp:Label ID="Label1" runat="server" Text="Select new role."></asp:Label>
<%:Html.DropDownListFor(model=>model.Roles,new SelectList (Model.Roles),null,new {id="roleName"}) %>
<input type="submit" value="Create" />
</div>
<% }%>
<%}%>
Model.Roles is an IEnumerable<String>
type;
it seems that changing the name of the parameter in the controller action gave me what I wanted:
public ActionResult AddUserRole (string userName,string roles)
{
if (Roles.IsUserInRole (userName,roles)==false)
{
Roles.AddUserToRole (userName,roles);
}
return RedirectToAction("Profile", "Profile",new {userName=userName});
}
<%
using (Html.BeginForm( "AddUserRole", "Account",new {userName=Model.UserName}))
{%>
<div id="AddRoleToUser">
<asp:Label ID="Label1" runat="server" Text="Select new role."></asp:Label>
<%:Html.DropDownListFor(model=>model.Roles,new SelectList (Model.Roles)) %>
<input type="submit" value="Create" />
</div>
<% }%>
<%}%>
not sure how I would alias that to something else, but for now it works so it'll be ok.
精彩评论