未使用 MVC3 C# 设置下拉列表值

Dropdownlist value not set with MVC3 C# [duplicate]
2021-11-25
  •  译文(汉语)
  •  原文(英语)

使用 Asp.net C#、MVC3 Razor View,我试图在编辑记录时设置下拉列表值并具有以下模型:

public class EditEmployeeModel
    {
        ....
        public int? DepartmentId { get; set; }

        [Required(ErrorMessage = "Department is must")]
        [Display(Name = "Department")]
        public string Department { get; set; }

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

        .....
}

控制器:

 public ActionResult Edit(string id)
    {
        EditEmployeeModel model = respo.GetEmployeeByID(id);
        model.Departments = GetDepartments();
        return View(model);
    }

并查看:

<div class="editor-field">
@Html.DropDownListFor(m => m.DepartmentId, Model.Departments, new { id ="ddlstDepartments"})
@Html.ValidationMessageFor(m => m.Department)
</div>

但是当加载视图进行编辑时,下拉列表总是显示选择的默认/第一个项目.有人可以在这里帮忙.

解决过程1

在将列表中的一个元素传递给视图之前,您是否尝试过为它设置 selected = true ?

So 上有几个问题可能会帮助你喜欢这个:

解决过程2

确保DepartmentIdin 模型

   EditEmployeeModel model = respo.GetEmployeeByID(id);
   //model.DepartmentId

不为空,如果您想--Select Department--按照@Karthik 建议的方式显示标签,请尝试

Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")

Working with Asp.net C#, MVC3 Razor View, I am trying to set dropdown list value while editing a record and have following Model:

public class EditEmployeeModel
    {
        ....
        public int? DepartmentId { get; set; }

        [Required(ErrorMessage = "Department is must")]
        [Display(Name = "Department")]
        public string Department { get; set; }

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

        .....
}

Controller:

 public ActionResult Edit(string id)
    {
        EditEmployeeModel model = respo.GetEmployeeByID(id);
        model.Departments = GetDepartments();
        return View(model);
    }

And View:

<div class="editor-field">
@Html.DropDownListFor(m => m.DepartmentId, Model.Departments, new { id ="ddlstDepartments"})
@Html.ValidationMessageFor(m => m.Department)
</div>

But when view is loaded for editing, dropdownlist always shows the default/first item selected. Could someone please help here.

Solutions1

Have you tried setting selected = true for one element in the list before passing it to view?

There are several questions on So that might help you like this one:

Solutions2

make sure the DepartmentId in model

   EditEmployeeModel model = respo.GetEmployeeByID(id);
   //model.DepartmentId

is not null, and if you want to show a --Select Department-- label as @Karthik suggested try

Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")
转载于:https://stackoverflow.com/questions/15240239/dropdownlist-value-not-set-with-mvc3-c-sharp

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入