How to use editortemplates in MVC3 for complex types?

I have two classes: Vat and Product. The product has the property IVat. I am trying to use editor templates in MVC to display a drop-down list of all Vat objects when creating / editing a product. For my dear life, I cannot get this work to work.

I have the following code that displays a drop-down list, but it does not set the Vat for the Product when the form is submitted.

Controller:

IList<IVatRate> vatRates = SqlDataRepository.VatRates.Data.GetAllResults(); ViewBag.VatRates = new SelectList(vatRates, "Id", "Description"); 

Add.cshtml

 @Html.EditorFor(model => model.VatRate.Id, "VatSelector", (SelectList)ViewBag.VatRates) 

VatSelector.cshtml

 @model SelectList @Html.DropDownList( String.Empty /* */, (SelectList)ViewBag.Suppliers, Model ) 

I would appreciate it if anyone could shed some light on this or even point me to a good example on the Internet somewhere ... I’ve been stuck with this for quite some days.

+6
source share
1 answer

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) { // model.SelectedVatRateId will contain the selected vat rate id ... } } 

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.

+7
source

Source: https://habr.com/ru/post/890355/


All Articles