It seems like there's a disconnect in the advised best practices when it comes to including the data source of a select list in a view model. For example, many best practices blog posts will recommend something along these lines:
ViewModel:
public class InvoiceViewModel
{
[UIHint("SelectInvoiceType")]
public int idInvoiceType { get; set; }
/* snip */
/* I'll use this in the view to generate a SelectList */
public List<invoicetype> InvoiceTypes { get; set; }
}
But then when we get to the editor template, the Model object will be just the int, with no knowledge of the containing view model:
SelectInvoiceType.cshtml
@model int
@{
Layout = "~/Views/Shared/_EditorFormItem.cshtml";
List<SelectListItem> selList = /* nothing to say here, really */;
}
@section DataContent {
@Html.DropDownListFor(m => Model, selList, null)
}
So, unless I'm missing something, these two "best practices" -- templated view helpers and strong开发者_运维问答ly-typed list data in the view model -- just can't be used together. You have to resort to stuffing your list data into the ViewBag. Sound about right?
Sorry to sound incredulous, but I feel like I must be missing something.
You have to resort to stuffing your list data into the ViewBag. Sound about right?
No. To me stuffing things in ViewBag/ViewData doesn't sound right. You should not use int
as a model type to an editor template that is supposed to generate a dropdownlist. A dropdownlist consists of two properties: a scalar type to bind the selected value to and a collection to be used to generate the different options in this ddl.
So a more correct way would be the following:
public class MyViewModel
{
[UIHint("SelectInvoiceType")]
public InvoiceTypesViewModel Invoice { get; set; }
... some other properties specific to the view
}
where InvoiceTypesViewModel
is a view model and doesn't contain any reference to domain models such as invoicetype
in the list in your example:
public class InvoiceTypesViewModel
{
public int SelectedInvoiceType { get; set; }
public SelectList InvoiceTypes { get; set; }
}
then in your main view:
@model MyViewModel
...
@Html.EditorFor(x => x.Invoice)
and the editor template:
@model InvoiceViewModel
@Html.DropDownListFor(m => m.SelectedInvoiceType, Model.InvoiceTypes)
精彩评论