2014-04-30 111 views
0

我一直在環顧四周,而且我無法完全找到有人試圖完成我的工作。我有幾個模型在一個頁面上一起工作。型號爲employees1,phone_managerphone_types在MVC中設置DropDownList的默認值

我設法讓插入工作得很好,但我似乎無法讓編輯頁面工作。我需要把當前存儲的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") 

任何幫助表示讚賞!

編輯

圖:

回答

1

一個好的做法是不要使用ViewBag。嘗試使用當前視圖所需的屬性創建一個簡單模型。

您還可以使用SelectList(IEnumerable, String, String, Object)過載SelectList其中對象是選定的值。只要使用此重載這樣的:

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

注:我有變化ViewBag.phone_type到ViewBag.phonetype。

+0

你能詳細解釋一下嗎?我試圖做類似的事情,但似乎我的員工模型幾乎包含了我需要的所有東西,但手機類型除外。問題是,我將不得不重複這個過程約6個不同的表格和計數,所以任何簡化我的努力是值得歡迎的。 –

+0

@Jdsfighter db.phone_types是保存所有手機類型數據的集合。我在創建操作的代碼中看到了這一點,並認爲這是您希望在下拉菜單中顯示的集合。 –

+0

@Jdsfighter如果你在ViewBag.phone_type之後,這是一個屬性,它應該有用戶在你想要指定的值之前選擇的值作爲下拉的默認值。您既可以使用ViewBag,也可以在視圖模型中創建一個字符串屬性。 –

2

這樣的事情引起了我小時的樂趣,尤其是應對signatures for the DropDownListFor overloads

時不管怎麼說,以下將下降產生的下降,並選擇包含在模型中的值。

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

如果你願意,你可以添加第三個說法,因爲HiddenFor方法做同樣的方式一個匿名對象,爲造型的目的。

+0

我可能只是補充說我最終放棄了ViewBag,就像我做的那樣不像強打字的損失。相反,我在業務邏輯層中使用了各種靜態方法,以便返回類型已經正確,並且不需要投射。 – barrick

+0

感謝您的幫助!這確實解決了我允許傳遞空值時遇到的一個問題,但它不會自動選擇默認值,它仍然只選擇第一個值。因爲我是新來的Asp.Net,我幾乎覺得我在看亂碼:/ –

+0

啊,我認爲這是因爲ViewBag屬性與模型的屬性名稱相同。嘗試將ViewBag屬性更改爲PhoneTypes或類似的東西。我編輯了答案來展示這一點。 – barrick

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到視圖模型 - 或者ViewBag如果你喜歡

查看:

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