Reputation: 8505
I have a List to pass to my view in 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");
}
Model:
[Required]
public String Reason { get; set; }
Veiw:
@model #####.ViewModels.ContactUs
@using (Html.BeginForm("ContactUs","Home", FormMethod.Post))
{
@Html.DropDownListFor(Model => Model.Reason, (IEnumerable<SelectListItem>) ViewBag.reasons);
}
I need to create a dropdownlist , perhaps DropDownList("reasons") (should be better way of writing this) form the ViewBag.reasons and pass the selected value to my Model, as property String Reason. Just confused about usage of the DropDownList/DropDownListFor. Thanks!
Upvotes: 0
Views: 14326
Reputation: 1038710
Model:
public class MyModel
{
[Required]
public String Reason { get; set; }
}
Controller:
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());
}
View:
@model MyModel
...
@Html.DropDownListFor(
x => x.Reason,
(IEnumerable<SelectListItem>)ViewBag.reasons,
"-- select a reason --"
)
but I would recommend you to get rid of ViewBag and use real view models:
public class MyViewModel
{
[Required]
public string Reason { get; set; }
public IEnumerable<SelectListItem> Reasons { get; set; }
}
and then the controller action will populate the view model and pass it to the view:
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);
}
and finally in your strongly typed view:
@model MyViewModel
...
@Html.DropDownListFor(
x => x.Reason,
Model.Reasons,
"-- select a reason --"
)
Upvotes: 7