Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post multi-select list to list of objects asp.net core 2

I have two classes called User and Role.

class User
{
    ...
    public List<Role> Roles;
}

class Role
{
    ...
    public int ID;
    public string Name;
}

I also 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)

like image 440
Alireza Mn Avatar asked Aug 22 '18 18:08

Alireza Mn


1 Answers

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"

like image 87
Xueli Chen Avatar answered Oct 25 '22 15:10

Xueli Chen