ASP.NET MVC 1.0 - Model Binder for Dictionaries

I have a ViewModel class containing a dictionary (and other irrelevant things for this question):

public class MyViewModel {
    public Dictionary<int, string> Data { get; set; }
    /* ... */
}

Then I have a couple of actions GET/ POSTthat relate to the dictionary. The action will GETfirst populate Dictionary<int, string>some data from the database, and then return View:

  • .Keywill be in hidden fields; and
  • .Value will be in the text field for editing by the user.

The user will then submit this form, triggering the action POST. It will try to process the input (the process does not matter). Some pairs Key/ Valuewill be valid , some will be invalid .

If there are invalid pairs, the action will POSTthen restore the ViewModel, but this time the dictionary should contain only pairs that are invalid and will re-display the same View for the user to be fixed and try sending again.

Question: What is the easiest and cleanest way to achieve this?

What I still (working fine) in the controller:

public ActionResult MyAction(MyViewModel vm) {
    /* Process data */
    if (are there invalid pairs?) {
        var vmErrors = new MyViewModel();
        /* ... fill the ViewModel ... */
        vmErrors.Data = 
            vm.Data
                .Where(x => IsInvalid(x))
                .ToDictionary(x => x.Key, x => x.Value);
        return View(vmErrors);
    }
}

And the view:

<% var i = 0; foreach (var p in Model.Data) { %>
    <%= Html.Hidden("vm.Data[" + i + "].key", vm.Key %>
    <%= Html.TextArea("vm.Data[" + i + "].value", vm.Value %>
<% i++; } %>

The problem is that in order to please the model binder, I have to specify my fields in the view with sequential identifiers. But I must also iterate over the dictionary to extract key / value pairs, so it cannot be a loop for (var i = 0; i < Model.Data.Count; i++) {...}.

+5
source share
1 answer

All Articles