Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlHelper.TextBox uses the model value even when an explicit value provided

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 the ViewDataDictionary object. If no value exists there, the value is retrieved from the ModelStateDictionary 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?

like image 807
GSerg Avatar asked Sep 04 '12 22:09

GSerg


2 Answers

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.

like image 119
Max Toro Avatar answered Oct 13 '22 00:10

Max Toro


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

like image 32
Slicksim Avatar answered Oct 13 '22 01:10

Slicksim