在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 (“理由”)(这应该是更好的编写方法)从ViewBag.reasons中创建,并将选择的值传递给Model,作为属性字符串原因。只是对DropDownList/DropDownListFor的用法感到困惑。谢谢!
发布于 2012-04-05 19:09:56
型号:
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 --"
)https://stackoverflow.com/questions/10034525
复制相似问题