选择SelectListItem进行建模

时间:2012-04-05 19:07:55

标签: asp.net-mvc asp.net-mvc-3 drop-down-menu

我有一个List传递给ViewBag中的我的视图:

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(“reason”)(应该是更好的编写方式)形成ViewBag.reasons并将选中的值传递给我的Model,作为属性String原因。只是混淆了DropDownList / DropDownListFor的用法。 谢谢!

1 个答案:

答案 0 :(得分: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 --"  
)