Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC Controller returning different views; Model data not being saved in hidden input
    primarykey
    data
    text
    <p>I'm attempting a multiple page form where I use a single controller action and returning a view depending on a value on my model.</p> <p>My model has a property that I put in an input field on my views, using Html.HiddenFor().</p> <p>Here's my simplified model:</p> <pre><code>public class MyModel { public virtual int Step { get; set; } } </code></pre> <p>And in my views, I have:</p> <pre><code>@model MyModel ... @Html.HiddenFor(model =&gt; model.Step) </code></pre> <p>Then in my controller I have:</p> <pre><code>public ActionResult Create() { ... myModel.Step = 1; return View("View1", myModel); } [HttpPost] public ActionResult Create(MyModel myModel) { ... if (myModel.Step == 1) { myModel.Step = 2; return View("View2", myModel); } else if (myModel.Step == 2) { ... } ... } </code></pre> <p>My problem is, my controller always sees mymodel.Step as having the value of 1. Why is that?</p> <p>What's weird is that I tried to display it on the form with these:</p> <pre><code>@Html.DisplayFor(model =&gt; model.Step) @Html.EditorFor(model =&gt; model.Step) </code></pre> <p>The second time the page was displayed, the first line showed the text "2". The second showed an input field with "1". I'm confused.</p> <p><strong>ADDITIONAL INFO:</strong></p> <p>My model also has a Guid property which is passed onto the View in a hidden field. I tried to change it also on postback, and check its value the second time around. The new value did not register. The model returned the original value before the first post. So it is consistent with the other field.</p> <p>I may have to use different controller actions if I couldn't find why it is behaving the way it does at the moment.</p> <p><strong>SOLUTION:</strong></p> <p>As Reda suggested below, I fixed it by doing this in my post action method:</p> <ul> <li>Before displaying "View2" and to effect changes my controller makes to a value in my model, I run ModelState.Clear()</li> </ul> <p>Here is a <a href="http://patrickdesjardins.com/blog/modelstate-clear-is-required-to-display-back-your-model-object" rel="nofollow">blog post</a> which confirms the need to clear ModelState for this scenario.</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.
    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