Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBoxFor displaying initial value, not the value updated from code [duplicate]

Tags:

c#

asp.net-mvc

Your problem is (step by step)

  1. Your SomeInformation() method sets the value of test1.Latitude to "LATITUDE2".
  2. You then pass that model to your Index() method using the overload of RedirectToAction that accepts an object. Internally this uses reflection to build a RouteValueDictionary based on the properties of your model (in this case its simply latitude="LATITUDE2").
  3. When you hit the Index method the model is bound by the DefaultModelBinder and now the value of DataSiteList.Latitude is "LATITUDE2" (which is why you enter the if block)
  4. In the process of binding, the DefaultModelBinder sets the ModelStatevalue of Latitude to "LATITUDE2". Any attempts to set the value of Latitude are now ignored because the view uses ModelState value to render the control.

It not clear what your trying to do here. You can make it work as you expect by adding ModelState.Clear(); as the first line of your Index() method. This clears all existing ModelState values an you can now set the value to "LATITUDE".

But your if block makes no sense. Perhaps you were just doing some kind of test, but you may as well remove the parameter from the Index() method and just initialize a new instance of DataSites in the method.

Edit

To give a bit more information as to why updating a model property has no affect once ModelState has been set.

Imagine you have a form to collect user information where the model contains int Age. The user is asked to enter their age and someone enters "I'm five next week!". Of course this wont bind to an int so the DefaultModelBinder adds the value (the attemptedValue) and adds a ModelStateError.

When the view is returned it will typically display an error message such as "The field Age must be a number". If the html helper rendering the control used the model value, then it would display "0" (the default value for int). It would be somewhat confusing for the user to see "0" in the textbox and next it a message saying it must be a number (What! but zero is a number and what the heck happened to what I entered?). So instead, the helper uses the value from ModelState and now the users sees "I'm five next week!" and an associated error message that makes sense for the value.

So even though you thoughts were that "its not logical", there is actually some logic to this behavior.