1

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

1
  • Could you paste your UserSignUpModel as well? Commented Dec 11, 2013 at 22:20

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

yep! it's because of ViewData! Asp.Net hides so much from developer, so sometimes it's really confusing
Can't do what your suggest ... When I used ViewData = null I was able to make Captcha = "" but the data I had on the ViewBag was deleted. Any other option?
1

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.

Comments

0

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" })

3 Comments

I added your two suggestions and not luck ... It is very strange that when I use model.Captcha = String.Empty; it still appears ... Any idea?
I just updated my post with the controller code ... I also tried to set the Email to "" and had the same result.
With HttpContext.Request.Params["Captcha"] = "" I get: An exception of type 'System.NotSupportedException' occurred in System.dll but was not handled in user code Additional information: Collection is read-only.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.