0

Suppose i have a model with a validation

public class LoginModel
{
    [Required(ErrorMessage="ID not entered")]
    [StringLength(5,ErrorMessage = "Length should be 5")]
    public string Id { get; set; }




}

In the view page i have a text box. When the validation fails. The controller returns to the view page with error message.

public ActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login(LoginModel lg)
    {
        if(ModelState.IsValid)
        {
            return RedirectToAction("Index", "Home");

        }
        return View();

    }

But the text box contains the previous values. How does it retains the value? And is there any way to avoid it?

Thanks

Thomas Mathew
  • 1,151
  • 6
  • 15
  • 30

2 Answers2

1

to delete the data just try the link which rattlemouse has posted -

ModelState.Clear()

or you do it manually with

 [HttpPost]
    public ActionResult Login(LoginModel lg)
    {
        if(ModelState.IsValid)
        {
            return RedirectToAction("Index", "Home");

        }
       else{
             lg.Id = string.Empty;
             return View(lg);
        }

    }
nWorx
  • 2,145
  • 16
  • 37
0

Clear ModelState and return view without model.

  ModelState.Clear();
  return View();

ModelState

Controller.ModelState Property

ModelState is a property of a Controller, and can be accessed from those classes that inherit from System.Web.Mvc.Controller. The ModelState represents a collection of name and value pairs that were submitted to the server during a POST. It also contains a collection of error messages for each value submitted.

LCJ
  • 22,196
  • 67
  • 260
  • 418