Note that there are some explanatory texts on larger screens.

plurals
  1. POIf value changes in Model after post, Form still displays old value
    primarykey
    data
    text
    <p>This behavior is making me wonder about my sanity..</p> <p>I have a form that has two places that accept input, let's call them ValueA and ValueB. The user can enter a value in either one and the form submits.</p> <pre><code>&lt;div id="MyUpdateTarget"&gt; &lt;% using (Ajax.BeginForm("MyControllerAction", new AjaxOptions { UpdateTargetId = "MyUpdateTarget" })) { %&gt; &lt;%=Html.TextBox("ValueA", Model.ValueA, new Dictionary&lt;string, object&gt; { { "onchange", "$('#SubmitButton').click(); return false;" }, }) %&gt; &lt;%=Html.TextBox("ValueB", Model.ValueB, new Dictionary&lt;string, object&gt; { { "onchange", "$('#SubmitButton').click(); return false;" }, }) %&gt; &lt;input id="SubmitButton" type="submit" value="Save" style="display: none;" /&gt; &lt;% } %&gt; &lt;/div&gt; </code></pre> <p>The Controller Action looks like this:</p> <pre><code>public ActionResult MyControllerAction(MyViewModel viewModel) { </code></pre> <p>// do some other stuff ...</p> <pre><code> return PartialView("MyPartialView", viewModel); } </code></pre> <p>The ViewModel is simply this:</p> <pre><code>public class MyViewModel { private int _valueA; private int _valueB; public int ValueA { get { return _valueA; } set { if (value &gt; 0) { ValueB = 0; } _valueA = value; } } public int ValueB { get { return _valueB; } set { if (value &gt; 0) { ValueA = 0; } _valueB = value; } } } </code></pre> <p>Now, the unexpected piece. Say the page initially loads and ValueB has a value of 7. The user changes ValueA to 5 and the form submits. I can put a breakpoint in the controller action and see both values in the viewModel parameter. At this point, ValueA is 5 and ValueB is 0 (due to the setting of ValueA). The action returns the viewModel as part of the PartialView. Back in the partial, I can put a breakpoint on the Html.TextBox("ValueB", Model.ValueB, ...) line and see that ValueB is indeed 0. But when the form renders to the browser, ValueB still has a value of 7. And this is where I am stuck. I have even changed the Update target to a different div, so that the partial just spits out the form someplace completely different, but it still has the original value of 7, even though I saw through debugging that the value was 0 coming back from the controller.</p> <p>Is there something I am missing?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload