Home > Net >  Clear One of Fields Value By ModelState In Asp.Net Core?
Clear One of Fields Value By ModelState In Asp.Net Core?

Time:09-17

I just want one field value to be empty

ModelState.Clear Clear all fields

Model :

 public class UserViewModel{
      [Required("")]
      public string Mobile { get; set; }
      [Required("")]
      public string Name { get; set; }
     }

Controller :

public IActionResult Create(UserViewModel viewModel){
   if (!ModelState.IsValid)
    {
      //clear just field "Name"
 
      return view(viewModel);
    }

  }

I want only the "Name" field to be cleaned when I return ?

CodePudding user response:

You can use ModelState.Remove("FieldName");

CodePudding user response:

try this

 if (ModelState.ContainsKey("Name")) ModelState.Remove("Name");

and better to use it this way

if (ModelState.ContainsKey("Name")) ModelState.Remove("Name");

if (!ModelState.IsValid)
    {
       return view(viewModel);
    }

if you want just clear the value

ModelState.SetModelValue("Name", new ValueProviderResult(string.Empty, CultureInfo.InvariantCulture));

since you don't clear errors and if it has errors, ModelState still will not be valid.

You can remove errors if you need

 ModelState["Name"].Errors.Clear();

CodePudding user response:

I used ViewBag, it worked better

public IActionResult Create(UserViewModel viewModel){
  if (!ModelState.IsValid)
   {
       ViewBag.value = ""; 
       return view(viewModel);
   }

}

Html :

<input id="answer" value="@ViewBag.value" asp-for="Name"/>
  • Related