Miguel Moura
Miguel Moura

Reputation: 39354

Set Html.TextBox value to null

I have the following textbox on an MVC view:

@Html.TextBoxFor(x => x.Captcha, new { @value = "" })

I am trying the textbox to always be empty when the form show after being submited with errors ... But this is not working. I always see the last value.

And this is my controller:

[Route("signup"), HttpGet]
public virtual ActionResult SignUp() {

  UserSignUpModel model = new UserSignUpModel();
  model.Captcha = String.Empty;
  model.Email = "";
  return View(model);

} // SignUp

[Route("signup"), HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult SignUp(UserSignUpModel model) {

  if (ModelState.IsValid) {

    // Create account code
    return View(MVC.Shared.Views._Note, new NoteModel("Account created"));

  } else {

    model.Captcha = String.Empty;
    model.Email = "";

    return View(Views.SignUp, model);

  }

}

Thank You, Miguel

Upvotes: 1

Views: 1857

Answers (3)

Miguel Moura
Miguel Moura

Reputation: 39354

I was able to solve this. The correct way is to use the model state:

ModelState["Captcha"].Value = new ValueProviderResult("", "", Thread.CurrentThread.CurrentCulture);

This way there is no need to clear other data in ViewData.

And by changing the ModelState, and not removing it, it becomes possible to still display the error associated with that property.

Upvotes: 1

Christopher.Cubells
Christopher.Cubells

Reputation: 911

If your form is submitted with errors, you can simply clear the ViewData and explicitly clear your property in the controller before returning the view with errors.

[HttpPost]
public ActionResult MyController(Model myModel)
{
    if (!ModelState.IsValid)
    {
        myModel.Captcha = String.Empty;

        ViewData = null;

        return View(myModel);
    }

    return View(myModel);
}

Upvotes: 1

Roman Pushkin
Roman Pushkin

Reputation: 6079

In your action method in your controller set this parameter manually:

// ...
model.Captcha = String.Empty;
return View(model);

And I recommend to add autocomplete=off html attribute to your captcha field:

@Html.TextBoxFor(x => x.Captcha, new { autocomplete = "off" })

Upvotes: 0

Related Questions