5

I am trying to create a workaround in my controller which handles a bug in ASP.NET MVC v1. The bug occurs if you post a listbox which has nothing selected (http://forums.asp.net/p/1384796/2940954.aspx).

Quick Explanation: I have a report that accepts two dates from textboxes and one or more selections from a ListBox. Everything works except for validation if the listbox is left with nothing selected.

When the form posts and reaches my controller, the model contains all items necessary. However, the ModelState does not contain a key/value for the listbox. To resolve, I was hoping something like this would do the trick:

if (!ModelState.ContainsKey("TurnTimeReportModel.Criteria.SelectedQueuesList") || ModelState["TurnTimeReportModel.Criteria.SelectedQueuesList"] == null) {
            ModelState.Keys.Add("TurnTimeReportModel.Criteria.SelectedQueuesList");
            ModelState["TurnTimeReportModel.Criteria.SelectedQueuesList"].Equals(new List<string>());
        }

Unfortuantely, this throws the following exception when I try to add the key: System.NotSupportedException: Mutating a key collection derived from a dictionary is not allowed.

Any ideas?

Thanks in advance!

PChristianFrost
  • 120
  • 2
  • 13
BueKoW
  • 926
  • 5
  • 18
  • 33

2 Answers2

5

Use the ModelState.Add method directly:

ModelState.Add("TurnTimeReportModel.Criteria.SelectedQueuesList", 
               new ModelState{ AttemptedValue = new List<string>() } )
womp
  • 115,835
  • 26
  • 236
  • 269
  • Thank you for the response! I will try this out and see how it performs in comparison. – BueKoW Jan 28 '10 at 20:39
  • Thanks for the good response! This also helped me out. Was facing this problem with a mocked controller in a unit test and this did the trick! – Rob Aug 23 '10 at 08:40
3

I ended up going with the following which has done the trick:

            if (ModelState.ContainsKey("TurnTimeReportModel.Criteria.SelectedQueuesList") && ModelState["TurnTimeReportModel.Criteria.SelectedQueuesList"] == null) {
            ModelState["TurnTimeReportModel.Criteria.SelectedQueuesList"].Value = new ValueProviderResult("", "", CultureInfo.CurrentUICulture);
        } else if (!ModelState.ContainsKey("TurnTimeReportModel.Criteria.SelectedQueuesList")) {
            ModelState.Add("TurnTimeReportModel.Criteria.SelectedQueuesList", new ModelState{Value = new ValueProviderResult("","",CultureInfo.CurrentUICulture)});
        }
BueKoW
  • 926
  • 5
  • 18
  • 33