Dmitry Borovsky
Dmitry Borovsky

Reputation: 558

Problem with HiddenFor helper

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.

Upvotes: 4

Views: 2367

Answers (1)

Steven K.
Steven K.

Reputation: 2106

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);
}

Upvotes: 4

Related Questions