Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a key does not exist in the ModelState, how can I add it? aspnetmvc1

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!

like image 589
BueKoW Avatar asked Jan 28 '10 19:01

BueKoW


People also ask

How do you add errors in ModelState?

Above, we added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

How do I get rid of ModelState error?

AddModelError() method to add a validationerror to the ModelState. If you then check the IsValid property in the ModelState variable, it will say its not valid. If you call ModelState. Clear() and then check the IsValid property again it will be valid.

Which property is used to determine an error in ModelState?

Errors property and the ModelState. IsValid property. They're used for the second function of ModelState : to store the errors found in the submitted values.

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.


1 Answers

Use the ModelState.Add method directly:

ModelState.Add("TurnTimeReportModel.Criteria.SelectedQueuesList", 
               new ModelState{ AttemptedValue = new List<string>() } )
like image 196
womp Avatar answered Nov 15 '22 03:11

womp