Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.