2012-04-05 71 views
0

我有一個列表傳遞給我的看法在ViewBag:選擇SelectListItem模型

public ActionResult ContactUs() 
    { 
     List<SelectListItem> reasons = new List<SelectListItem>(); 
     reasons.Add(new SelectListItem 
     { 
      Selected = true, 
      Text = "Billing/Payment question", 
      Value = "Billing/Payment question" 
     }); 
     reasons.Add(new SelectListItem 
     { 
      Text = "Complaint", 
      Value = "Complaint" 
     }); 

     ViewBag.reasons = reasons; 
     return View(); 
    } 

[HttpPost] 
public ActionResult ContactUs(ContactUs form) 
{ 
    //some code 
    return View("ContactUs"); 
} 

型號:

[Required] 
public String Reason { get; set; } 

教職員:

@model #####.ViewModels.ContactUs 
@using (Html.BeginForm("ContactUs","Home", FormMethod.Post)) 
{ 
    @Html.DropDownListFor(Model => Model.Reason, (IEnumerable<SelectListItem>) ViewBag.reasons); 
} 

我需要創建一個下拉列表,也許DropDownList(「原因」)(應該是更好的書寫方式)形成ViewBag.reasons,並通過選擇將td值賦給我的Model,作爲屬性String Reason。只是混淆了DropDownList/DropDownListFor的使用。 謝謝!

回答

7

型號:

public class MyModel 
{ 
    [Required] 
    public String Reason { get; set; } 
} 

控制器:

public ActionResult Index() 
{ 
    var reasons = new List<SelectListItem>(); 
    reasons.Add(new SelectListItem 
    { 
     Selected = true, 
     Text = "Billing", 
     Value = "Billing" 
    }); 
    reasons.Add(new SelectListItem 
    { 
     Text = "Complaint", 
     Value = "Complaint" 
    }); 
    ViewBag.reasons = reasons; 
    return View(new MyModel()); 
} 

查看:

@model MyModel 
... 
@Html.DropDownListFor(
    x => x.Reason, 
    (IEnumerable<SelectListItem>)ViewBag.reasons, 
    "-- select a reason --" 
) 

但我會建議你擺脫ViewBag和使用真正的視圖模型:

public class MyViewModel 
{ 
    [Required] 
    public string Reason { get; set; } 

    public IEnumerable<SelectListItem> Reasons { get; set; } 
} 

,然後控制器動作將填充視圖模型,並將其傳遞給視圖:

public ActionResult MyAction() 
{ 
    var reasons = new List<SelectListItem>(); 
    reasons.Add(new SelectListItem 
    { 
     Text = "Billing", 
     Value = "Billing" 
    }); 
    reasons.Add(new SelectListItem 
    { 
     Text = "Complaint", 
     Value = "Complaint" 
    }); 

    var model = new MyViewModel 
    { 
     // Notice how I am using the Reason property of the view model 
     // to automatically preselect a given element in the list 
     // instead of using the Selected property when building the list 
     Reason = "Billing", 
     Reasons = reasons 
    }; 

    return View(model); 
} 
在強類型視圖

最後:

@model MyViewModel 
... 
@Html.DropDownListFor(
    x => x.Reason, 
    Model.Reasons, 
    "-- select a reason --" 
) 
+0

我知道你的意思,但對於這種情況,只需要在ViewBag中傳遞列表即可。萬分感謝。 – mishap 2012-04-05 19:12:34

+3

@Chuchelo,好,我只是有義務指出良好的做法。你可以忽略它們並繼續使用ViewBag。 – 2012-04-05 19:14:50

+0

我得到和以前一樣的錯誤:「沒有ViewData項的類型爲'IEnumerable ',它有'Reason'鍵。」任何想法爲什麼?代碼被編譯。 – mishap 2012-04-05 19:14:58