How to add specific user to table when you have many in one List in asp net core mvc

Solution for How to add specific user to table when you have many in one List in asp net core mvc
is Given Below:

I have in one view two submit buttons

The First one search for users in Active directory

The Second one Add selected user to table AspNetUsers

I have specified username which is staff id in button attribute asp-route-id so that I can add that specific user from the list of users that will appear after clicking the search button. but the problem is that it add the first person in the list. it doesn’t add the one I clicked on.

This is my controller


[AcceptVerbs("Get", "Post")]
        
        public async Task<IActionResult> AddUser(SearchViewModel profile , string button, List<User> users  )
        {
            
            if (button == "Search")
            {
                if (ModelState.IsValid)
                {

                    users = new List<User>();
                    

                    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.com"))
                    {
                        UserPrincipal qbeUser = new UserPrincipal(ctx);
                        qbeUser.DisplayName = profile.Name + "*";

                        using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
                        {
                            if (!string.IsNullOrEmpty(srch.FindAll().ToString()))
                            {
                                foreach (var found in srch.FindAll())
                                {
                                    if (found != null)
                                    {
                                        
                                            users.Add(new User()
                                            {
                                                Name = found.Name,
                                                Email = found.UserPrincipalName,
                                                SatffID = found.SamAccountName
                                            });
                                        
                                        
                                        
                                    }
                                    else
                                    {
                                        return View();
                                    }



                                }
                                SearchViewModel returnmodel = new SearchViewModel(users);
                                return View(returnmodel);
                            }
                        }
                    }
                }
            }
            if(button=="Add")
            {
                if (ModelState.IsValid)
                {
                    
                        var user = new ApplicationUser { UserName = profile.ID, Email = profile.Email,  DisplayName = profile.DisplayName };

                        var result = await userManager.CreateAsync(user);
                    
                        if (result.Succeeded)
                        {
                        if(profile.Location !=null)
                        {
                            for (int i = 0; i < profile.Location.Count; i++)
                            {
                                
                                var newUser = await userManager.FindByNameAsync(profile.ID);
                                var userId = newUser.Id;
                                //var newUser = profile.ID;
                                UserLocation userLoc = new UserLocation
                                {
                                    UserID = userId.ToString(),
                                    LocID = profile.Location[i]
                                };
                                userLocation.Add(userLoc);
                            }
                            return RedirectToAction("Index", "Home");

                        }
                        ModelState.AddModelError(string.Empty, "No locs");


                    }
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }

                        ModelState.AddModelError(string.Empty, "");

                   
                    
                        
                    
                   
                        
                    
                           
                   
                }
                return View(profile);
            }
                
               
                return View(profile);
            
            
        }
        

This is my View AddUser

@model SearchViewModel


<h1>Add New User</h1>
@Html.ValidationSummary(true)
<form method="post" formaction="">

    <div id="content">

        <fieldset>
            <div class="form-group col-md-12">
                @Html.LabelFor(model => Model.Name, new { @class = "control-label col-md-2" })
                <div class="col-md-4">
                    @Html.EditorFor(modelItem => Model.Name, new { htmlAttributes = new { @class = "form-control", @style = "width:280px" }, })

                </div>
                <div>
                    <div class="form-group row">
                        <label asp-for="@Model.Location" class="col-sm-2 col-form-label"></label>
                        <div class="col-sm-10">
                            <select asp-for="@Model.Location" asp-items="Html.GetEnumSelectList<Location>()" class="custom-select mr-sm-2" id="Subjects_dropdown" multiple>
                                <option value="">Please Select</option>
                            </select>
                            <span asp-validation-for="@Model.Location" class="text-danger"></span>

                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <input type="submit" class="btn btn-default" name="button" value="Search">

                </div>
                <div class="col-md-3">
                </div>
            </div>
        </fieldset>

        <br>

    </div>


    <table id="historyTable" class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Staff Id</th>
                <th>Add User</th>
            </tr>
        </thead>
        <tbody>


            @if (Model.FoundUsers != null)
            {
                @foreach (var user in Model.FoundUsers)
                {
                    if (user != null)
                    {
                        <tr>

                            <td><label asp-for="DisplayName"></label><input asp-for="DisplayName" value="@user.Name" name="displayname" /></td>
                            <td><label asp-for="Email"></label><input asp-for="Email" value="@user.Email" name="Email" /></td>
                            <td><label asp-for="ID"></label><input asp-for="ID" value="@user.SatffID" name="ID" /></td>
                            <td><input type="submit"  class="btn btn-primary" name="button" value="Add" asp-route-Id="@user.SatffID" asp-action="AddUser"></td>
                        </tr>
                    }



                }

            }
            else
            {
                <tr>
                    <td colspan="4">No Record Available</td>
                </tr>
            }





        </tbody>
    </table>
</form>

}
@section Scripts{
    <script>
        $(document).ready(function () {
            $('#Subjects_dropdown').multiselect();
        });
       
    </script>
}







I try to reproduce your issue in my side, and I found that if I click Add button, the request contains all rows data like screenshot below:

enter image description here

So I think the issue comes from the form submit, I tried to add form for each row, and it worked.

Here’s my code snippet, just adding @using (Html.BeginForm()) for content。

Here’s a similar question as yours, and you can also refer to it to write js script to achieve it.

My controller action:

[AcceptVerbs("Get", "Post")]
        public IActionResult AddUser(SearchViewModel profile, string button, List<User> users)
        {
            ViewData["Location"] = new List<string> {
                "location_a",
                "location_b"
            };
            if (button == "Search")
            {
                if (ModelState.IsValid)
                {
                    users = new List<User>();
                    users.Add(new User()
                    {
                        Name = "name_a",
                        Email = "email_a",
                        SatffID = "staff_a"
                    });
                    users.Add(
                    new User()
                    {
                        Name = "name_b",
                        Email = "email_b",
                        SatffID = "staff_b"
                    });
                    users.Add(
                    new User()
                    {
                        Name = "name_c",
                        Email = "email_c",
                        SatffID = "staff_c"
                    });
                    SearchViewModel returnmodel = new SearchViewModel();
                    returnmodel.FoundUsers = users;
                    return View(returnmodel);
                }
            }
            if (button == "Add")
            {
                if (ModelState.IsValid)
                {

                    var user = new ApplicationUser { UserName = profile.ID, Email = profile.Email, DisplayName = profile.DisplayName };
                    //save data
                    return RedirectToAction("Index", "Home");
                }
                return View(profile);
            }
            return View(profile);
        }

View code :

@model SearchViewModel

<h1>Add New User</h1>
@Html.ValidationSummary(true)
<form method="post" formaction="">
    <div id="content">
        <fieldset>
            <div class="form-group col-md-12">
                @Html.LabelFor(model => Model.Name, new { @class = "control-label col-md-2" })
                <div class="col-md-4">
                    @Html.EditorFor(modelItem => Model.Name, new { htmlAttributes = new { @class = "form-control", @style = "width:280px" }, })
                </div>
                <div>
                    <div class="form-group row">
                        <label asp-for="@Model.Location" class="col-sm-2 col-form-label"></label>
                        <div class="col-sm-10">
                            <select asp-for="@Model.Location" asp-items="(@ViewData["Location"] as IEnumerable<SelectListItem>)" class="custom-select mr-sm-2" id="Subjects_dropdown" multiple>
                                <option value="">Please Select</option>
                            </select>
                            <span asp-validation-for="@Model.Location" class="text-danger"></span>

                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <input type="submit" class="btn btn-default" name="button" value="Search">

                </div>
                <div class="col-md-3">
                </div>
            </div>
        </fieldset>
        <br>
    </div>

    <table id="historyTable" class="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Staff Id</th>
                <th>Add User</th>
            </tr>
        </thead>
        <tbody>
            @if (Model.FoundUsers != null)
            {
                @foreach (var user in Model.FoundUsers)
                {
                    if (user != null)
                    {
                        <tr>
                            @using (Html.BeginForm())
                            {
                                <td><label asp-for="DisplayName"></label><input asp-for="DisplayName" value="@user.Name" name="displayname" /></td>
                                <td><label asp-for="Email"></label><input asp-for="Email" value="@user.Email" name="Email" /></td>
                                <td><label asp-for="ID"></label><input asp-for="ID" value="@user.SatffID" name="ID" /></td>
                                <td><input type="submit" class="btn btn-primary" name="button" value="Add" asp-route-Id="@user.SatffID" asp-action="AddUser"></td>
                            }
                        </tr>
                    }
                }
            }
            else
            {
                <tr>
                    <td colspan="4">No Record Available</td>
                </tr>
            }
        </tbody>
    </table>
</form>

@section Scripts{
    <script>
        $(document).ready(function () {
            $('#Subjects_dropdown').multiselect();
        });
    </script>
}

This is what related code I only added

enter image description here