4

Model:

public sealed class Model
{
    public string Value { get; set; }
}

Controller:

[HandleError]
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new Model { Value = "+" } );
    }

    [HttpPost]
    public ActionResult Index(Model model)
    {
        model.Value += "1";
        return View(model);
    }
}

View:

<%using (Html.BeginForm()){%>
  <%: Model.Value %>
  <%: Html.HiddenFor(model => model.Value) %>
  <input type="submit" value="ok"/>
<%}%>

Every time I submitted form result is

<form action="/" method="post">+1
<input id="Value" name="Value" type="hidden" value="+">
<input type="submit" value="ok">
</form>

It means that HiddenFor helper doesn't use real value of Model.Value but uses passed to controller one. Is it bug in MVC framework? Does anyone know workaround?

UPDATE: EditerFor works similar.

Dmitry Borovsky
  • 558
  • 7
  • 23
  • http://stackoverflow.com/questions/594600/possible-bug-in-asp-net-mvc-with-form-values-being-replaced – Jahan Zinedine Dec 30 '10 at 08:31
  • I have posted an explanation of the issue: **why isn't it by design that the Model is used, which is set explicitly by the developer and if a validation error occurred, the ModelState is used** And a really simple and effective solution to fix this issue exactly wihout using weird workarounds. [possible-bug-in-asp-net-mvc-with-form-values-being-replaced](http://stackoverflow.com/questions/594600/possible-bug-in-asp-net-mvc-with-form-values-being-replaced/30698787#30698787) – Dacker Jun 07 '15 at 22:16

1 Answers1

4

This will fix your problem, however it's not a recommended solution.

More info can be found here: http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

[HttpPost]
public ActionResult Index(Model model)
{
    model.Value += "1";

    ModelState.Clear();

    return View(model);
}

[Edit]

Another option if you don't want to use <input id="Value" name="Value" type="hidden" value="<%: Model.Value %>"/>

[HttpPost]
public ActionResult Index(FormCollection collection)
{
    var m = new Model();

    m.Value = collection["Value"] + "1";

    return View(m);
}
Steven K.
  • 2,097
  • 16
  • 15
  • Did you even read the article? Use `` instead of `ModelState.Clear();` – Mike Dec 30 '10 at 09:42
  • Well, if you clear the ModelState you get rid of all the data that was entered by users when there are some errors. What is wrong with HTML in HTML? – Mike Dec 30 '10 at 10:17
  • 1
    Bad is that we can't use useful helper methods. It means that we should generate id and name attributes by oneself, for example. – Dmitry Borovsky Dec 30 '10 at 10:22