在MVC中设置DropDownList的默认值

时间:2014-04-30 21:21:57

标签: c# asp.net sql-server asp.net-mvc entity-framework

我一直在四处寻找,而且我找不到有人试图做我自己的事情。我有几个模型在一个页面上一起工作。模型为employees1phone_managerphone_types

我设法让插入工作正常,但我似乎无法使编辑页面正常工作。我需要将当前存储的phone_type这是一个外键phone_type_id,并将其作为我的组合框中的默认项。

我的模特是:

[Table("employee.employees")]
public partial class employees1
{

    public employees1()
    {
        employee_email_manager = new List<email_manager>();
        employee_employment_history = new HashSet<employment_history>();
        employee_job_manager = new HashSet<job_manager>();
        employee_phone_manager = new HashSet<phone_manager>();
        this.salaries = new HashSet<salary>();
    }

    [Key]
    public int employee_id { get; set; }
    [Display(Name = "Employee ID")]
    public int? assigned_id { get; set; }

    [Display(Name = "Web User ID")]
    public int? all_id { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "First Name")]
    public string first_name { get; set; }

    [StringLength(50)]
    [Display(Name = "Last Name")]
    public string last_name { get; set; }

    [Column(TypeName = "date")]
    [Display(Name = "Birthday")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime birth_day { get; set; }

    [Required]
    [StringLength(1)]
    [Display(Name = "Gender")]
    public string gender { get; set; }

    [Required]
    [StringLength(128)]
    [Display(Name = "Social")]
    public string social { get; set; }

    [Required]
    [StringLength(128)]
    [Display(Name = "Address")]
    public string address_line_1 { get; set; }

    [StringLength(50)]
    [Display(Name = "Suite/Apt#")]
    public string address_line_2 { get; set; }

    [Required]
    [StringLength(40)]
    [Display(Name = "City")]
    public string city { get; set; }

    [Required]
    [StringLength(20)]
    [Display(Name = "State")]
    public string state { get; set; }

    [Required]
    [StringLength(11)]
    [Display(Name = "Zip")]
    public string zip { get; set; }

    [Column(TypeName = "date")]
    [Display(Name = "Hire Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime hire_date { get; set; }

    [Column(TypeName = "date")]
    [Display(Name = "Separation Date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime? termination_date { get; set; }

    [StringLength(70)]
    [Display(Name = "Emergency Contact Name")]
    public string emergency_contact_name { get; set; }

    [StringLength(15)]
    [Display(Name = "Emergency Contact Number")]
    public string emergency_contact_phone { get; set; }

    [Display(Name = "Notes")]
    public string notes { get; set; }

    public virtual all_employees all_employees { get; set; }
    [Display(Name = "Email Addresses")]
    public virtual ICollection<email_manager> employee_email_manager { get; set; }
    [Display(Name = "Employment History")]
    public virtual ICollection<employment_history> employee_employment_history { get; set; }
    [Display(Name = "Position History")]
    public virtual ICollection<job_manager> employee_job_manager { get; set; }
    [Display(Name = "Phone Numbers")]
    public virtual ICollection<phone_manager> employee_phone_manager { get; set; }

    internal void CreatePhoneNumbers(int count = 1)
    {
        for (int i = 0; i < count; i++)
        {
            employee_phone_manager.Add(new phone_manager());
        }
    }

    [Table("employee.phone_manager")]
    public partial class phone_manager
    {
        /*public phone_manager()
        {
            phone_types = new HashSet<phone_types>();
        }*/

        [Key]
        public int phone_id { get; set; }

        public int employee_id { get; set; }

        [Required]
        [StringLength(15)]
        [Display(Name="Phone Number")]
        public string phone_number { get; set; }

        [StringLength(5)]
        [Display(Name = "Extension")]
        public string phone_extension { get; set; }

        [Display(Name = "Type")]
        public int phone_type { get; set; }

        [Column(TypeName = "date")]
        public DateTime date_added { get; set; }

        public bool deleted { get; set; }

        public virtual employees1 employees1 { get; set; }
        [ForeignKey("phone_type")]
        public virtual phone_types phone_types { get; set; }
        //public virtual ICollection<phone_types> phone_types { get; set; }
    }

    [Table("employee.phone_types")]
    public partial class phone_types
    {
        public phone_types()
        {
            phone_manager = new HashSet<phone_manager>();
        }

        [Key]
        public int phone_type_id { get; set; }

        [Required]
        [StringLength(50)]
        public string phone_type_name { get; set; }

        public virtual ICollection<phone_manager> phone_manager { get; set; }
    }
}

我的控制器:

    public ActionResult Create()
    {
        ViewBag.all_id = new SelectList(db.all_employees, "all_id", "all_id");
        var employee = new employees1();
        ViewBag.phone_type = new SelectList(db.phone_types, "phone_type_id", "phone_type_name");
        employee.CreatePhoneNumbers(1);
        return View(employee);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="employee_id,assigned_id,all_id,first_name,last_name,birth_day,gender,social,address_line_1,address_line_2,city,state,zip,hire_date,termination_date,emergency_contact_name,emergency_contact_phone,notes,employee_phone_manager")] employees1 employees1)
    {
        if (ModelState.IsValid)
        {
            foreach (employees1.phone_manager phone in employees1.employee_phone_manager.ToList())
            {
                if (phone.deleted == true)
                {
                    employees1.employee_phone_manager.Remove(phone);
                }
            }
            db.employees1.Add(employees1);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        var employee = new employees1();
        ViewBag.phone_type = new SelectList(db.phone_types, "phone_type_id", "phone_type_name");
        ViewBag.all = new SelectList(db.all_employees, "all_id", "all_id", employees1.all_id);
        return View(employees1);
    }

    // GET: /Employees/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        employees1 employees1 = db.employees1.Find(id);
        if (employees1 == null)
        {
            return HttpNotFound();
        }
        var employee = new employees1();
        ViewBag.phone_type = new SelectList(db.phone_types, "phone_type_id", "phone_type_name");
        ViewBag.all_id = new SelectList(db.all_employees, "all_id", "all_id", employees1.all_id);
        return View(employees1);
    }

    // POST: /Employees/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include="employee_id,assigned_id,all_id,first_name,last_name,birth_day,gender,social,address_line_1,address_line_2,city,state,zip,hire_date,termination_date,emergency_contact_name,emergency_contact_phone,notes")] employees1 employees1)
    {
        if (ModelState.IsValid)
        {
            db.Entry(employees1).State = EntityState.Modified;
            db.SaveChanges();
            foreach (var item in employees1.employee_phone_manager)
            {
                db.Entry(item).State = EntityState.Modified;
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        var db2 = new LightHouseMain();
        var employee = new employees1();
        ViewBag.phone_type = new SelectList(db.phone_types, "phone_type_id", "phone_type_name");
        ViewBag.all_id = new SelectList(db.all_employees, "all_id", "all_id", employees1.all_id);
        return View(employees1);
    }

我的观点:

     @Html.LabelFor(x => x.phone_type)
    @Html.DropDownList("phone_type", string.Empty)
    @Html.LabelFor(x => x.phone_number)
    @Html.TextBoxFor(x => x.phone_number, new { @class = "phone", size = "10" })
    @Html.LabelFor(x => x.phone_extension)
    @Html.TextBoxFor(x => x.phone_extension, new { size = "4" })
    @Html.HiddenFor(x => x.date_added, new { @Value = System.DateTime.Now })
    @Html.HiddenFor(x => x.deleted, new { @class = "mark-for-delete" })
    @Html.RemoveLink("Remove", "div.phoneNumber", "input.mark-for-delete")

感谢任何帮助!

编辑

图:

3 个答案:

答案 0 :(得分:2)

这种事情让我有了几个小时的乐趣,特别是在处理signatures for the DropDownListFor overloads

无论如何,以下内容将生成一个下拉列表并选择模型中包含的值。

@Html.DropDownListFor(x => x.phone_type, (SelectList)ViewBag.PhoneTypes)

如果您愿意,可以添加第三个参数,一个匿名对象,与HiddenFor方法一样,用于样式化。

答案 1 :(得分:1)

一个好的做法是不使用ViewBag。尝试使用当前视图所需的属性创建一个简单模型。

您还可以使用SelectList的{​​{3}}重载,其中对象是所选值。只需使用这样的重载:

ViewBag.phonetype = new SelectList(db.phone_types, "phone_type_id", "phone_type_name", Model.phone_type );

注意:我已将ViewBag.phone_type更改为ViewBag.phonetype。

答案 2 :(得分:0)

你可能需要在这里做一些更重的提升。

循环浏览列表以构建下拉列表并在点击时设置所选值。

如果我误读了你的数据结构,请道歉,但这是理论:

控制器:

var phoneTypeList = new Dictionary<int, string>();
foreach (var pt in db.phone_types)
{
    phoneTypeList.Add(pt.phone_type_id, phone_type_name);

    if (pt.phone_type_id == employees1.phone_types.phone_type_id)
    {
         selectedValue = pt.phone_type_id;
    }
}

然后将phoneTypeList和selectedValue添加到viewmodel - 或ViewBag(如果你喜欢)

查看:

@Html.DropDownListFor(x => x.phone_type, new SelectList(Model.phoneTypeList, "Key", "Value", Model.selectedValue);