Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear field value if ModelState says the field is invalid

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] = "";
    }
  }
}
like image 215
user482833 Avatar asked Dec 21 '22 07:12

user482833


1 Answers

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);
}
like image 125
João Angelo Avatar answered Dec 28 '22 06:12

João Angelo