123
123

Reputation: 105

How to clear the post data for a textbox in an ASP.NET MVC application?

By default, a textbox rendered using <%= Html.TextBox("somefield")%> uses the value from the post data, e.g. if you have validation errors on your page, the value is retrieved from the posted data and used for the value attribute.

Now, in a few cases I want to be able to clear that value, in other words I want the textbox to be blank, I don't want MVC to get the value from the posted data and uses it for the value attribute, how can I do? How can I clear the post data?

Thanks

Upvotes: 7

Views: 9907

Answers (3)

TTT
TTT

Reputation: 28934

I found I had to both remove the ModelState and change the model, as if MVC tries ModelState first, then the model:

ModelState.Remove("key");
model.key = "";

And if you don't want to lose your Error state for the model, you can just change the value like this:

ModelState.SetModelValue("Captcha", new ValueProviderResult(null, string.Empty, System.Globalization.CultureInfo.InvariantCulture));
model.key = "";

Upvotes: 3

SLaks
SLaks

Reputation: 887423

Remove the value from the model state, like this:

ViewData.ModelState.Remove("somefield");

Upvotes: 3

ChaosPandion
ChaosPandion

Reputation: 78262

ModelState.Remove("key");

Upvotes: 12

Related Questions