Search code examples
c#asp.net-mvcasp.net-coreasp.net-mvc-4blazor

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


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 ?


Solution

  • 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"/>