问题
I have two classes called User and Role. User is like this
class User{
...
public List<Role> Roles;
}
and Role is like this
class Role{
...
public int ID;
public string Name;
}
now I have an action (Submit)
public IActionResult Submit(User user){
...
}
in my index.cshtml select
is
<select multiple="multiple" class="multi-select" id="my_multi_select1" asp-for="Roles" asp-items="ViewBag.Roles"></select>
and ViewBag.Roles
value is
ViewBag.Roles= new SelectList(Role.SelectAll(), "Name", "Name");
the problem is that when I post my form, data is sent like this
...&Roles=role1,role2&...
and so user.Roles becomes null while I want to make two Roles with names role1
and role2
and assign them to user.Roles (Actually I want Asp does that)
回答1:
The Select Tag Helper asp-for specifies the model property name for the select element and asp-items specifies the option elements(a collection of SelectListItem ),rather than object collection.
1.Add a ViewModel with a List as the property for your dropdown items.
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<int> Roles { get; set; }
}
2.In.cshtml file select like below
@model PostMultiSelect.Models.UserViewModel
<select multiple="multiple" class="multi-select" id="my_multi_select1" asp-for="@Model.Roles" asp-items="(List<SelectListItem>)ViewBag.Roles"></select>
3.The value of ViewBag.Roles like below, get the Roles with RoleId
ViewBag.Roles = _context.Roles.Select(r=>new SelectListItem { Value=r.ID.ToString(),Text=r.Name}).ToList();
If you want to get Roles with name ,you could change "Value=r.ID.ToString()" to"Value=r.Name"
来源:https://stackoverflow.com/questions/51973284/post-multi-select-list-to-list-of-objects-asp-net-core-2