(I'm new to MVC).
In my application I don't have a model in the sense of a class with properties. Oh no it's much simpler: my users basically fill in a bunch of string values for various keys setup elsewhere in the system (the keys are arbitrary and not known ahead of time, thus no pre-coded class)1.
My "model" thus is just:
Dictionary<string, string>
Pretty simple.
As I understand it model binding, html helpers, model state, validation summaries all rely on reflection of an arbitrary class' properties. But can they just use the key/values in my dictionary instead?
For example, can I have:
<label for="Name">Name:</label>
<%= Html.TextBox("Name") %>
<%= Html.ValidationMessage("Name", "*") %>
and:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dictionary<string, string> valuesEntered)
{
// ...
}
and have MVC use the "Name"
key/value as found in my Dictionary<string, string>
"model" to do all its behind-the-scenes magic? (MVC 1.0 preferrably, but please shed some light if this is better addressed in 2.0 as I'd still like to know)?
1: sounds silly I'm sure. It's for a reporting app, where the "keys" are the report parameter names and the "values" are the values the report will run with.
The default model binder in MVC 1.0 can bind to a dictionary as long as it uses the magic form field identifiers 'dictionaryName[index].key' and 'dictionaryName[index].value', where dictionaryName is the name of your dictionary parameter, and index is a 0-based sequential number. Typically the 'key' value will be a hidden field, and the 'value' value is your text field. In your example:
<%= Html.Hidden("valuesEntered[0].key", "Name") %>
<%= Html.TextBox("valuesEntered[0].value") %>
<%= Html.ValidationMessage("valuesEntered[0].value", "*") %>
As I understand it, binding to dictionaries is different in MVC 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With