0

我有一个列表要传递给我在 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 ,也许 DropDownList("reasons") (应该是更好的编写方式)形成 ViewBag.reasons 并将选定的值作为属性 String Reason 传递给我的模型。只是对 DropDownList/DropDownListFor 的使用感到困惑。谢谢!

4

1 回答 1

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 --"  
)
于 2012-04-05T19:09:56.977 回答