4

I want to clear the submitted value of a field in a model if the ModelState shows that the field is not valid.

This is where I have got so far but can't tie up the key to value in the model. Any suggestions?

if (!ModelState.IsValid)
{
  foreach (string key in ModelState.Keys)
  {
    if (!ModelState.IsValidField(key))
    {
       // This field is not valid so set to empty string in model
       // Something like....
       model[key] = "";
    }
  }
}
João Angelo
  • 56,552
  • 12
  • 145
  • 147
user482833
  • 111
  • 2
  • 8

1 Answers1

11

You should return the same view with the received model and also change your code to the following:

if (!this.ModelState.IsValidField(key))
{
    var emptyValue = new ValueProviderResult(
        string.Empty,
        string.Empty,
        CultureInfo.CurrentCulture);

    this.ModelState.SetModelValue(
        key,
        emptyValue);
}
João Angelo
  • 56,552
  • 12
  • 145
  • 147
  • I know this is an old question. But as an extension to this question --> How do we access the model with updated values, if I dont want my model to hold invalid values. – user979737 Oct 06 '15 at 23:01