I’m looking to store arithmetic expressions to a database. I have this db structure:
Expression
=======
id
name
Operand
=======
id
expressionId
value
side (indicates if the operand is on the left or right side of the expression)
idx (the index to identify the order of operands on each side)
Operator
========
id
expressionId
type
side
idx
In my View, I want to provide the user the ability to create an expression with a variable number of operands and operators by adding controls dynamically to the page upon request. If the user clicks the “Add operand” button, a dropdown will be generated for the operator via javascript, and a textbox will be generated for the operand.
My thought is to use custom model binding in my expression’s Create action and work with a viewmodel:
public class ExpressionCreateViewModel
{
IEnumerable<ExpressionOperator> Operators { get; set; }
IEnumerable<ExpressionOperand> Operands { get; set; }
Expression Expression { get; set; }
}
The model binder would work with it:
public class ExpressionCreateViewModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var vm = new ExpressionCreateViewModel();
//Build it!
}
What I’m leery of is how I would have to pass in the dynamically generated control’s values into this view model. The only way I can think of doing it is creating control IDs that provide all the details (e.g. <input type=”text” id=”operand:1$side:left”>)
Then I could parse through the items in the form collection and by convention build the operand and operator objects.
Does anyone have a cleaner way to do this?
Thanks!
Chris
The normal way to bind to collection properties in a view model is to use array notation in the naming of your Html elements. For example:
Depending on what you need, the default binder may even do this work for you.