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] = "";
}
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With