In a view I'm using this overload of HtmlHelper.TextBox
:
public static MvcHtmlString TextBox(
this HtmlHelper htmlHelper,
string name,
Object value
)
The documentation states:
value
Type:
System.Object
The value of the text input element. If this value is
null
, the value of the element is retrieved from theViewDataDictionary
object. If no value exists there, the value is retrieved from theModelStateDictionary
object.
I do provide a value
when I call this overload, and this value is not null. Nevertheless, the value for the textbox is retrieved from the ModelStateDictionary
whenever it is present there.
In order to force the textbox to use the value provided inline, I have to reset the model first in the controller (or remove the key with the textbox's name from the keys collection).
Same applies to other controls rendered by HtmlHelper
.
Where is my understanding wrong? Or is that a bug in the documentation?
ModelState
always has precedence in all input helpers, not just TextBox
. This allows you to specify a default value in the view, and after POST render the posted value (taken from ModelState) without having to manually pass the posted value to the view. To use a different value you must remove the entry from ModelState.
This is how the model binder works, it takes the values from the modelstate, probably to preserve the values from a failed postback or validation failure. Have you tried using the Html attributes to set the value
Html.TextBox("Id", new { Value = Model.Id})
Si
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With