I am currently trying to figure out how you can bind multiple fields in an MVC 3 view to 1 property on a view model and what is recommended when trying to achieve this.
Using an example for the number of minutes (only) that it takes to prepare something.
The form might look something like this:
Preparation time - Hours: [ 1 ] Minutes: [ 30 ]
and the submitted form values need to be converted into minutes and bound to the PreparationTimeInMinutes property of the ViewModel.
ViewModel property:
public short PreparationTimeInMinutes { get; set; }
and the View is strongly typed to the ViewModel and currently has the below:
<div class="editor-label">
@Html.LabelFor(model => model.PreparationTimeInMinutes)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PreparationTimeInMinutes)
@Html.ValidationMessageFor(model => model.PreparationTimeInMinutes)
</div>
Here are a few things that I began thinking about in order to achieve this.
- Change the PreparationTimeInMinutes property to a ViewModel that has an hour & minute property and create Editor and display templates for it so that MVC3 can sort out the binding and validation?
- Use javascript and a hidden field for the preparation time.
- Some other approach that lets you use the MVC model binding to do this sort of thing?
Does anyone have any suggestions on best practice for this sort of thing? or if I am way off.
Please let me know. Thanks