I am using MVC5 ASP.Net with Razor Engine for a view that has following html helper for displaying a textbox and setting its value to ViewBag.SearchText.
When user inputs text into this textbox and view posts back, then the value is set correctly according to value in ViewBag.SearchText, but when in controller's action the ViewBag.SearchText = string.Empty, then textbox still retains its original value rather than an empty string.
Is this how the Html helper for textbox is supposed to behave Or I am missing something, and how could I set the value of textbox to an empty string? This is quite strange since the ViewBag.SearchText value is an empty string when I step through code in Visual Studio 2013.
@Html.TextBox("SearchText", (string)ViewBag.SearchText)
UPDATE 1:
I found that using the code Model.Clear() at start of the controller action solved this problem. However, I found another way to just clear that part of ModelState that is used to populate the textbox after postback. The key in ModelState is the id of the textbox, which is 'SearchText'. The code for this is as below.
ModelState.SetModelValue("SearchText", new ValueProviderResult(null,string.Empty,
System.Globalization.CultureInfo.InvariantCulture));
That's by default (ModelState
retains the value on post back).
You can use ModelState.Clear()
before setting ViewBag.SearchText = "";
and returning the view. However use with caution because clearing ModelState
can have unexpected results if your using validation