user2232861
user2232861

Reputation: 283

How to get ModelState Errors at runtime using Key added by ModeState.AddModelError( key,value)

I have added Model error from controller using

if( model property not selected) { ModelState.AddModelError("SelectionRequired","Please select atleast one value"); }

This error I am adding at many places in that same method but ultimately I want to show to user only one such message out of the ModelState errors collection.

For that purpose before returning to view I have to remove all similar messages except one.

How can i remove this messages using "SelectionRequired" i.e. key and not using "Please select atleast one value".This "SelectionRequired" is not a model property name is just a key we want to use.

I checked ModelState.Keys collection at runtime I don't see the "SelectionRequired" at all in those collection and also not even in ModelState.Values collection. Then where does this key *"SelectionRequired" goes ? and how to select errors based on it ?

is there any better way to do this ?

Upvotes: 1

Views: 1798

Answers (1)

Marko
Marko

Reputation: 33

This might work:

var error = ModelState["SelectionRequired"].Errors.First();
ModelState["SelectionRequired"].Errors.Clear();
ModelState["SelectionRequired"].Errors.Add(error);

Upvotes: 2

Related Questions