I would use strongly typed views and view models as this makes things a lot simpler than the ViewBag.
So, start with a view model:
public class VatRateViewModel { public string SelectedVatRateId { get; set; } public IEnumerable<IVatRate> Rates { get; set; } }
then the controller:
public class HomeController: Controller { public ActionResult Index() { var model = new VatRateViewModel { Rates = SqlDataRepository.VatRates.Data.GetAllResults() }; return View(model); } [HttpPost] public ActionResult Index(VatRateViewModel model) {
View:
@model VatRateViewModel @using (Html.BeginForm()) { @Html.DropDownListFor( x => x.SelectedVatRateId, new SelectList(Model.Rates, "Id", "Description") ) <input type="submit" value="OK" /> }
And if you want to use the editor template for VatRateViewModel, you can define it in ~/Views/Shared/EditorTemplates/VatRateViewModel.cshtml :
@model VatRateViewModel @Html.DropDownListFor( x => x.SelectedVatRateId, new SelectList(Model.Rates, "Id", "Description") )
and then whenever you have a property of type VatRateViewModel , you can simply:
@Html.EditorFor(x => x.SomePropertyOfTypeVatRateViewModel)
which displays the corresponding editor template.
source share