在ASP.NET MVC中填充下拉菜单的正确方法

时间:2018-09-09 14:53:40

标签: javascript c# jquery asp.net asp.net-mvc

这就是我从模型中实现下拉菜单的方式。我只想检查这是否是正确的方法,还是有更简单的方法?似乎很令人费解。

我的列表的模型:

Author

进入我的视图的视图模型

public class ApplicationRolesDropdownListDetailViewModel
{
    public String RoleId { get; set; }
    public String ApplicationRoleName { get; set; }
}

获取项目列表并将其放在视图的下拉列表中的控制器:

public class ApplicationRolesDropdownListViewModel
{
    public SelectList Roles { get; set; }
}

我的观点:

    public ActionResult NewRole()
    {
        var applicationRoles = applicationRolesData.GetAllApplicationRoles();
        ApplicationRolesDropdownListViewModel ardlvm = new ApplicationRolesDropdownListViewModel();
        ardlvm.Roles = new SelectList(applicationRoles, "RoleId", "ApplicationRoleName");
        return View("~/Views/Users/Modals/AddRole.cshtml", ardlvm);
    }

此外,当我通过javascript从列表中选择一项时,我似乎无法获得RoleId。

编辑:添加了我的GetApplicationRoles

    <div class="form-group">
        @Html.DropDownListFor(m => m.Roles,Model.Roles, new { @id = "role", @class = "dropdown" })
    </div>

1 个答案:

答案 0 :(得分:2)

尝试这样

ViewModel

public class ApplicationRolesViewModel
{
    // Display Attribute will appear in the Html.LabelFor
    [Display(Name = "User Role")]
    public string RoleId { get; set; }
    public IEnumerable<SelectListItem> Roles { get; set; }
}

控制器

public ActionResult NewRole()
    {
        var roleData = new IEnumerable<SelectListItem>();
        applicationRolesData.GetAllApplicationRoles().Foreach(x =>
                   roleData.Add( new SelectListItem
                        {
                            Value = x.RoleId.ToString(),
                            Text = x.ApplicationRoleName
                        });
       );
        ApplicationRolesViewModel ardlvm = new ApplicationRolesViewModel();
        ardlvm.Roles = new SelectList(roleData , "Value", "Text")
        return View("~/Views/Users/Modals/AddRole.cshtml", ardlvm);
    }

查看

@model ApplicationRolesViewModel

@Html.LabelFor(m => m.RoleId)
@Html.DropDownListFor(m => m.RoleId, Model.Roles)

并在Jquery中获得下拉菜单的当前选定值:

$('#RoleId').val();

要获取当前选定的文本,请执行以下操作:

$('#RoleId:selected').text();