Home > Back-end >  ASP.net multiple select always returns 0 selected items
ASP.net multiple select always returns 0 selected items

Time:05-03

So i'm trying to build a User multi-select in order to get the participants to a project. This is my code:

  <form asp-page-handler="ProjectModalPartial">
                @*numele metodei*@
                <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
                <div >
                    <label asp-for="ProjectsModel.ProjectName">Title</label>
                    <input asp-for="ProjectsModel.ProjectName"  placeholder="MyProject1" />
                    <span asp-validation-for="ProjectsModel.ProjectName" ></span>
                </div>
                <br />
                <div >
                    <label asp-for="ProjectsModel.ProjectDescription">Description</label>
                    <textarea asp-for="ProjectsModel.ProjectDescription"  rows="3" placeholder="This is my first project"></textarea>
                    <span asp-validation-for="ProjectsModel.ProjectDescription" ></span>
                </div>
                <br />

                <div >

                    <label asp-for="ProjectsModel.MultiValues">Project participants</label>
                    <select multiple="multiple"  id="listbox1" asp-for="ProjectsModel.MultiValues" asp-items="@Model.Items" style="width: 470px;">
                     
                    </select>
                    <span asp-validation-for="ProjectsModel.MultiValues" ></span>

                </div>
            </form>

The page:

 public ApplicationDbContext _context;

    public ProjectsList(ApplicationDbContext context)
    {
        _context = context;
    }

    public List<Project> ProjectList { get; private set; } = new List<Project>();
    [BindProperty]
    public ProjectsModel ProjectsModel { get; set; }
    public List<User> UserList { get; private set; } = new List<User>();

    public IEnumerable<SelectListItem> Items { get; set; }
    = new List<SelectListItem>();
    public void OnGet()
    {

        ProjectList =  _context.Projects.ToList();
        Items = (from usr in this._context.Users
                 select new SelectListItem
                 {
                     Text = usr.Email.ToString(),
                     Value = usr.Id.ToString()
                 }).ToList();


    }

    public IActionResult OnPostProjectModalPartial()
    {
        Items = (from usr in this._context.Users
                 select new SelectListItem
                 {
                     Text = usr.Email.ToString(),
                     Value = usr.Id.ToString()
                 }).ToList();

        if (ModelState.IsValid)
        {
            var project = new Project
            {
                ProjectName = ProjectsModel.ProjectName,
                ProjectDescription = ProjectsModel.ProjectDescription,
                Created = DateTime.Now,
                Active = true,
                ProjectCreatorId = User.FindFirst(ClaimTypes.NameIdentifier).Value

            };
            _context.Projects.Add(project);
            _context.SaveChanges();
            foreach (var person in Items)
            {
                _context.ProjectParticipants.Add(new ProjectParticipant
                {
                    ProjectId = project.Id,
                    UserId = person.Value
                });


            }
            _context.SaveChanges();
        }
        return Page();
    }

And the model:

   public class ProjectsModel
{
    public int Id { get; set; }
    [Required]
    public string ProjectName { get; set; }
    [Required]
    public string ProjectDescription { get; set; }
    public DateTime Created { get; set; }
    public bool Active { get; set; }

    public string ProjectCreatorId { get; set; }

    [Required(ErrorMessage = "You must select atleast one participant")]
    public List<User> ProjectParticipants { get; set; }

    public IEnumerable<string> MultiValues { get; set; }


}

However, when i put a breakpoint inside the foreachloop of OnPostProjectModalPartial i can see the list is populated with all the users but none of them is selected. What am i doing wrong? Do i need some jquery script to make this work?

CodePudding user response:

You need indicate the property of your model associated to the selected option:

<select multiple="multiple" 
    
   id="listbox1" 
   asp-for="UserId" // <-- This property
   asp-items="@Model.Items" 
   style="width: 470px;">

And add UserId property to your class:

public int UserId { get; set; }

Then, in the post, your model UserId has the selected user id and you can do a query to get all info that you need about that user.

NOTE: In your current OnPostProjectModalPartial, you are making a query in your database but without any kind of selection info getted from the post.

CodePudding user response:

If you want some of the list of users selected you need to change your code, this piece of code in the page part

ORIGINAL

foreach (var person in Items)
{
    _context.ProjectParticipants.Add(new ProjectParticipant
    {
         ProjectId = project.Id,
         UserId = person.Value
     });
} //ORIGINAL

Into this: Filtering only the Model.Iems selected

foreach (var person in model.Items.Where(item=> item.Selected))
{
    _context.ProjectParticipants.Add(new ProjectParticipant
    {
         ProjectId = project.Id,
         UserId = person.Value
     });
}

Also you did'nt need to go get the list again from database, you got it in the model

  • Related