I am trying to populate a "Company" dropdown but I can not get the Razor syntax correct on it. With the below code it makes my modal just not pop up. JS gets an undefined error for the company field and it errors out. If i remove @Html.DropDownListFor(c => c.SelectedCompany, Model.CompanyLists, "- Please select a state -", new { @class = "form-control" })
then the modal pops up fine, just with no items populated.
Any idea what I am doing wrong? I was using this article for reference. https://nimblegecko.com/using-simple-drop-down-lists-in-ASP-NET-MVC/ ; however, it has a hard-coded list instead of one pulling from DB.
<div class="tab-pane fade show active" id="user" role="tabpanel" aria-labelledby="user-tab">
<form method="post" class="mt-3">
<div class="form-group row text-center">
<label asp-for="Id" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input disabled asp-for="Id" class="formField inputDisabled" disabledclass="form-control">
</div>
</div>
<div class="form-group row text-center">
<label asp-for="FirstName" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="FirstName" class="formField" />
<span asp-validation-for="FirstName" class="text-danger"></span>
/div>
</div>
<div class="form-group row text-center">
<label asp-for="LastName" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="LastName" class="formField" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="Title" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="Title" class="formField" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="Email" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="Email" class="formField" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="UserName" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="UserName" class="formField" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="CompanyLists" class="col-sm-3 text-right col-form-label labelFont"></label>
@*ISSUE IS HERE--------------------------------------------------------------------------------------*@
<div class="col-md-5">
@Html.DropDownListFor(c => c.SelectedCompany, Model.CompanyLists, "- Please select a state -", new { @class = "form-control" })
@Html.ValidationMessageFor(c => c.SelectedCompany, "", new { @class = "text-danger" })
</div>
@*------------------------------------------------------------------------------------------*@
</div>
<div class="form-group row text-center">
<label asp-for="Address" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="Address" class="formField" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="City" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="City" class="formField" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="State" class="col-sm-3 text-right col-form-label labelFont"></label>
<div class="col-sm-8">
<input asp-for="State" class="formField" />
<span asp-validation-for="State" class="text-danger"></span>
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<button type="submit" class="btn btn-primary padFloat btnBlue" asp-action="EditUser" asp-controller="Administration" asp-route-id="@Model.Id">Update</button>
<a asp-action="UserMaint" class="btn btn-primary padFloat btnRed">Cancel</a>
</form>
</div>
Model:
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; }
}
}
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,
//CompanyId = user.CompanyId
};
// ViewBag.SelectedCommpany = user.CompanyId;
//COMPANY DROPDOWN INFO------------------------------------
var company = from c in companyRepository.GetCompanys() select c;
foreach (var c in company)
{
////Store this inforamtion 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);
}
ViewBag.UserModel = model;
return PartialView("~/Views/Modals/_EditUserModalPartial.cshtml", model);
}
Follow my example
Here is my DropDownListFor;
@Html.DropDownListFor(model => Model.SelectedDropDownValue, new SelectList(Model.DropDownListAutoPopulate), "Quarter - Year", new { @class = "form-control btn-primary form-control", @id = "QuarterYearConcat", @onchange = @"form.submit();" })
Model.SelectedDropDownValue
is the selected value passed back from the controller
public List<string> DropDownListAutoPopulate { get; set; }
is the list that will populate the dropdown. Which is my viewModel model.
Here is my full model for the viewModel
namespace MoCApp.ViewModels
{
public class SLGAdminCreateViewModel
{
public SLGHeader SLGHeader;
[Range(-100.00, 100.00, ErrorMessage = "Value must be between -100 and 100")]
public decimal? TotalBudget { get; set; }
[Range(-100.00, 100.00, ErrorMessage = "Value must be between -100 and 100")]
public decimal? TotalLaborBudget { get; set; }
public List<QuarterWeekType> DropDownList { get; set; }
public SLGQuarterDetails SLGQuarterList { get; set; }
public QuarterWeekType Dropdown { get; set; }
public string SelectedDropDownValue { get; set; }
public List<string> DropDownListAutoPopulate { get; set; }
}
}
Here is my Get method in relation to the model and view.
// GET: SLG/CreateAdmin
[Authorize(Roles = "WFL_APP_MOCHUB-Admins,WFL_APP_SLG-Admins,Managers,WFL_ROLE_StoreManagmentTeams")]
public ActionResult CreateAdmin(SLGAdminCreateViewModel value)
{
// ViewModel for Both Forms
var viewModel = new SLGAdminCreateViewModel
{
SLGHeader = new SLGHeader(),
DropDownList = new List<QuarterWeekType>(),
DropDownListAutoPopulate = new List<string>(),
TotalBudget = null,
TotalLaborBudget = null
};
// Formating returned value for query to set values.
if (value.SelectedDropDownValue != null)
{
var QuarterYear = value.SelectedDropDownValue.Replace("Q", "").Replace(":", "").Replace(" ", "");
var Quarter = decimal.Parse(QuarterYear.Substring(0, 1), CultureInfo.InvariantCulture);
var Year = decimal.Parse(QuarterYear.Substring(1, 4), CultureInfo.InvariantCulture);
var TotalBudgetList = db.QuarterDetails.Where(x => x.Quarter == Quarter && x.Year == Year && x.Store == 1 && x.Department == "total")
.ToList();
foreach (var x in TotalBudgetList) { viewModel.TotalBudget = x.TotalBudget; viewModel.TotalLaborBudget = x.TotalLaborBudget; };
}
// Format dropdown list
viewModel.DropDownList = db.SLGHeaderTemplates.Where(x => x.Year > 2018 && x.Week == 1).Select(x => new QuarterWeekType { Year = x.Year, Quarter = x.Quarter, QuarterYearConcat = "" }).ToList();
foreach (var item in viewModel.DropDownList)
{
item.QuarterYearConcat = "Q" + Convert.ToInt32(item.Quarter) + " : " + Convert.ToInt32(item.Year);
}
foreach (var x in viewModel.DropDownList) { viewModel.DropDownListAutoPopulate.Add(x.QuarterYearConcat); };
return View(viewModel);
}
If you follow my example and have your model, view and controller in the same relations. You will be golden.
Don't mind my logic with me foreaching through one object and putting it into another list. Just know where your list goes in the DropDownListFor statement and how it is related to your viewModel and Controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.