Search code examples
asp.netasp.net-mvcasp.net-corerazorasp.net-identity

Setting DropdownList Value using asp.NET Core Identity


I have a bit of a mess I am trying to clean up. I have a Company dropdownlist that is getting populated correctly. But I can't figure out how to get the the selected value for the dropdown working. I've looked at many examples but with the context we are using this, it's confusing for me. We are using asp.Net Core Identity.

Any guidance is appreciated!

Dropdown List:

   <div class="form-group row text-center">
     <label asp-for="CompanyLists" class="col-sm-3 text-right col-form-label labelFont"></label>
       <div class="col-sm-8">
         @Html.DropDownListFor(model => model.SelectedCompany, new SelectList(Model.CompanyLists.OrderBy(x => x.CompanyName), "CompanyID", "CompanyName"), "-- Select Company --", new { @class = "form-control" })
           <span asp-validation-for="CompanyLists" class="text-danger"></span>
       </div>
   </div>

Method:

        // EDIT USER : GET-----------------------------------------------------
        [HttpGet]
        public async Task<IActionResult> EditUser(string id)
        {
            //GET USER INFORMATION - EXIT IF USER DOESN'T EXIST
            var user = await userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
                return View("NotFound");
            }

     //USER INFORMATION ---------------------------------------
            var model = new EditUserViewModel
            {
                Id = user.Id,
                Email = user.Email,
                UserName = user.UserName,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Title = user.Title,
                Address = user.Address,
                City = user.City,
                State = user.State,
                //SelectedCompany = user.Company.ToString()
            };

    //COMPANY DROPDOWN INFO------------------------------------
            var company = from c in companyRepository.GetCompanys() select c;
            foreach (var c in company)
            {
                ////Store this information into the company list in the viewmodel
                var companyinfo = new EditUserViewModel.CompanyList
                {
                    CompanyName = c.CompanyName,
                    CompanyID = c.CompanyId,
                };

                model.CompanyLists.Add(companyinfo);
            };

     //GET LIST OF ROLES(RoleID, RoleName)
            var roles = roleManager.Roles;

            foreach (var RoleName in roles)
            {
                //Execute identity method to get full information for the Role and store into an object (roleinfo)
                var roleString = RoleName.Name;
                var fullRoleInfo = await roleManager.FindByNameAsync(roleString);
                //Store this information into the Role list in the viewmodel
                var roleinfo = new EditUserViewModel.Role
                {
                    RoleName = fullRoleInfo.Name,
                    RoleID = fullRoleInfo.Id,
                };

                if (await userManager.IsInRoleAsync(user, roleString))
                {
                    roleinfo.IsSelected = true;
                }
                else
                {
                    roleinfo.IsSelected = false;
                }

                model.Roles.Add(roleinfo);
            };

     //*****************************************************
            //IDENTITY CLAIM INFORMATION ------------------------------

            var existingUserClaims = await userManager.GetClaimsAsync(user);

            foreach (Claim claim in ClaimStore.AllClaims)
            {
                var userClaims = new EditUserViewModel.Claim
                {
                    ClaimType = claim.Type
                };


                if (existingUserClaims.Any(c => c.Type == claim.Type && c.Value == "true"))
                {
                    userClaims.IsSelected = true;
                }
                else
                {
                    userClaims.IsSelected = false;
                }

                model.Claims.Add(userClaims);
            }

       return PartialView("~/Views/Modals/_EditUserModalPartial.cshtml", model);
      }

This is where I start to get confused. We have an EditUserViewModel.cs; however, we also have ApplicationUser.cs model and I can't figure out how the selected company into ApplicationUser.cs or whatever I need to do to make this work.

EditUserViewModel:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace PortalDev.Models.ViewModels
{
    public class EditUserViewModel
    {

        public EditUserViewModel()
        {
            Claims = new List<Claim>();
            Roles = new List<Role>();
            //CompanyLists = new List<ICompanyRepository>();
            CompanyLists = new List<CompanyList>();
        }

        //ROLES ---------------------------------------------
        public class Role
        {
            public string RoleName { get; set; }
            public string RoleID { get; set; }
            public bool IsSelected { get; set; }

        }
        public List<Role> Roles { get; set; }

        //CLAIMS----------------------------------------------
        public class Claim
        {
            public string ClaimType { get; set; }
            public string ClaimID { get; set; }
            public bool IsSelected { get; set; }
        }
        public List<Claim> Claims { get; set; }

        //COMPANY DROPDOWN--------------------------------------
        public class CompanyList
        {
            public string CompanyName { get; set; }
            public int CompanyID { get; set; }
        }
        [Display(Name = "Company")]
        public List<CompanyList> CompanyLists { get; set; }   //List of Companies for dropdown
        public string SelectedCompany { get; set; }


        //USER INFORMATION --------------------------------------
        public string Id { get; set; }
        //[Required]
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public int CompanyId { get; set; }
    }
}

ApplicationUser.cs

using Microsoft.AspNetCore.Identity;
using PortalDev.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
//Extends built in IdentityUser class
namespace PortalDev.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }

        public string Address{ get; set;}
        public string City { get; set; }
        public string State { get; set; }

        public Company Company { get; set; }
    }
}

UserMaint.html

@model IEnumerable<PortalDev.Models.ApplicationUser>

<link rel="stylesheet" href="~/css/Maintenance.css" />
<link rel="stylesheet" href="~/css/Index.css" />


<div class="tableContainer">

    <div class="maintHeader">
        <div class="headerText">
            All Users

            <button class="sqButton btnBlue float-right" title="Register" data-toggle="ajax-modal" data-target="#register" data-url="@Url.Action("Register", "Home")"><i class="glyphicon glyphicon-plus"></i></button>
        </div>
    </div>

    @if (Model.Any())
    {
        //--Table Header Declaration--
        <div class="wrapper">
            <div class="scrollTable">

                <table class="table table-hover table-md ">

                    <thead>
                        <tr>
                            <th class="text-left tableHead d-none">Id</th>
                            <th class="text-left tableHead">Company</th>
                            <th class="text-left tableHead">User Name</th>
                            <th class="text-left tableHead">First Name</th>
                            <th class="text-left tableHead">Last Name</th>
                            <th class="text-left tableHead">Title</th>
                            <th class="text-left tableHead">City</th>
                            <th class="text-left tableHead">State</th>
                            <th class="text-left tableHead text-right">Remove</th>
                        </tr>
                    </thead>

                    @*--Table Body For Each to pull DB records--*@
                    <tbody>
                        @foreach (var user in Model)
                        {
                            @Html.Partial("~/Views/Administration/Users/UserTable.cshtml", user)
                        }
                    </tbody>

                </table>
            </div>
        </div>

    }
    <div id="modal-placeholder"></div>
</div>


Solution

  • If you want to show the Company that the user had before the edit on the EditUser.cshtml, you could make the following modification on ApplicationUser model , EditUser method and the dropdownlist like below:

    ApplicationUser.cs

    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
    
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    
        public int CompanyId { get; set; }
        [ForeignKey("CompanyId")]
        public Company Company { get; set; }
    }
    

    EditUser method

    var model = new EditUserViewModel
     {
                Id = user.Id,
                Email = user.Email,
                UserName = user.UserName,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Title = user.Title,
                Address = user.Address,
                City = user.City,
                State = user.State,
                CompanyId = user.CompanyId
     };
    

    Company DropdownList

    <div class="col-sm-8">
      @Html.DropDownListFor(model => model.CompanyId, new SelectList(Model.CompanyLists.OrderBy(x => x.CompanyName), "CompanyID", "CompanyName"), "-- Select Company --", new { @class = "form-control" })
      <span asp-validation-for="CompanyId" class="text-danger"></span>
    </div>