Asp.net Mvc和Core,它是如何工作的SelectListItem

时间:2017-10-06 20:56:10

标签: asp.net asp.net-mvc selectlistitem

enter image description here 我在编辑操作中有用户编辑问题..当涉及到departmentDropdownlist时 当我点击一个用户进行编辑时,假设他/她属于管理员,我想要显示 在下拉列表和下面的管理中,所有部门都在同一下拉列表中。 但是现在当我点击编辑它以Id顺序向我显示所有部门..就像我想添加一个新用户。 我有角色下拉列表。这是好事。如果用户是Employee ..它首先显示Employee然后显示其余的Role列表..如果用户是Admin,那么它显示我Admin 然后低于角色列表的其余部分。但是当谈到部门时,它会向我显示DeptId = 1的第一个部门名称,依此类推。我试过Asp.Net Mvc和Core。这是我的EditUser和EditUserViewModel

[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
    EditUserViewModel model = new EditUserViewModel();
    model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
    {
        Text = r.Name,
        Value = r.Id
    }).ToList();

    model.DepartmentNames = context.Departments.Select(s => new SelectListItem
    {

        Text = s.DeptName,
        Value = s.DeptId.ToString()
    }).ToList();

    if (!String.IsNullOrEmpty(id))
    {
        ApplicationUser user = await userManager.FindByIdAsync(id);
        if (user != null)
        {
            model.Name = user.Name;
            model.Email = user.Email;
            model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;
            model.DeptId = context.Departments.Single(r => r.DeptName == context.Sites.....??????); //How to do here
                                                                                                    // ViewBag.DeptId = new SelectList(context.Departments, "DeptId", "DeptName", model.DeptId); // Even like this , shows the first id departmentname

        }
    }
    return PartialView("_EditUser", model);
}

我的EditUserViewModel

public class EditUserViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public List<SelectListItem> ApplicationRoles { get; set; }

    public string ApplicationRoleId { get; set; }

    public List<SelectListItem> DepartmentNames { get; set; }

    public int DeptId { get; set; }   // I have DeptId too in my AspNetUser table
}

1 个答案:

答案 0 :(得分:0)

由于DepartmentId表格有model.DeptId,我不知道你为什么不指定model.DeptId = context.Departments.Single(r => r.DeptName == context.Sites.....??????);

所以而不是

DepartmentId

您可以从用户表中分配model.DeptId = user.DepartmentId; ,即

TagHelper

使用<select class="form-control" asp-for="DeptId" asp-items="DepartmentNames"></select> 构建下拉列表时,在Razor上,应根据ID选择正确的下拉选项值。

private void cmbSort_SelectedIndexChanged(object sender, EventArgs e)
{
    DataTable dt = lst_CustomerNo.DataSource as DataTable;
    if(cmbSort.SelectedItem == "A-Z")
        dt.DefaultView.Sort = "OrderName ASC";
    else
        dt.DefaultView.Sort = "OrderName DESC";
}