views:

426

answers:

2

I have a list of items in my form which are named like this...

<input type="text" id="ListItem1" name="ListItem1">
<input type="text" id="ListItem2" name="ListItem2">
<input type="text" id="ListItem3" name="ListItem3">

I want to create a custom model binder which converts these in to model with this structure...

public class MyModel
{
  public IEnumerable<MyModelItem> Items {get; set;}
}

public class MyModelItem
{
  public int Id { get; set; }
  public string Value { get; set; }
}

So each ListItem should be converted to a MyModelItem with id equal to the number at the end of the input id and value set to the value on the input field.

In ASP.Net MVC 1.0 I could iterate over the bindingContext.ValueProvider.Keys collection and check for key.StartsWith("ListItem") to find all input items in this format.

The new IValueProvider interface in ASP.Net MVC 2 does not have a keys collection and I cannot iterate over that interface. How can I access these values which I only know the prefix for at design time in ASP.Net MVC 2?

A: 

Could you use the bindingContext.ModelState.Keys collection?

Update Sorry, should have been a bit clearer. What I meant was could you not use the ModelState.Keys collection, check for key.StartsWith("ListItem") and if so use that key to get the value from the value provider (using the GetValue method).

Chao
Nope, the ModelState does not hold the posted form values :-(
Noob
+1  A: 

If you want to iterate over the form values, use Request.Form.

Levi
Yep, this appears to be the only way to do this. This makes testing the model binder messy though as faking out the request variables involves overriding the HttpContextBase and HttpRequestBase classes. Also, I feel that I'm missing something here. They must have removed this functionality for a reason right? Am I doing something that I shouldn't be doing?
Noob
The functionality was removed because it was limiting. It forced all value providers to be enumerable, when in reality some value providers (like value providers that point to arbitrary objects) cannot be enumerable. In cases like yours, where you know that the data is in Request.Form and you don't even know the proper keys until runtime, going against Request.Form is the proper solution. The ValueProvider is just an unnecessary abstraction in your case.
Levi