1

I have a simple MVC controller and view and model (I removed all other codes to figure out the problem) Model is a simple one property class:

public class SiteFileUploadModel
{
    [Required]
    public int ActivePage { get; set; }
}

View is also very simple:

@model Models.SiteFileUploadModel
@{
      ViewBag.Title = "Index";
 }
 <h2>Index</h2>
 @if (Model != null)
 {
      using (this.Html.BeginForm("Index", "SiteFileUpload"))
      {
           @Html.Hidden("ActivePage",Model.ActivePage)
           @Model.ActivePage
           switch (Model.ActivePage)
           {
                case 1:
                    <p>Page 1</p>
                    break;
                case 2:
                    <p>Page 2</p>
                    break;
           }
           <button type="submit" name="actionButtons">Previous</button>
           <button type="submit" name="actionButtons">Next</button>
      }
  }

The controller has only one method:

public class SiteFileUploadController : Controller
{
    //
    // GET: /FileUpload/SiteFileUpload/
    [HttpGet]
    public ActionResult Index()
    {
        var model = new SiteFileUploadModel();
        model.ActivePage = 1;
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SiteFileUploadModel model, string actionButtons)
    {
        if (actionButtons == "Next")
        {
            model.ActivePage++;

        }
        if (actionButtons == "Previous")
        {
            model.ActivePage--;
        }

        return View(model);
    }

}

When I am running it and press next, I can see that model.activePage became 2 and it also shows on output (it shows 2 and page 2), but the hidden value is still 1. In fact the hidden value is always 1 and it doesn't follow the real value of ActivePage. I also tested it with generating hidden field using HiddenFor(m=>m.ActivePage) with the same effect! What is the problem?

tereško
  • 58,060
  • 25
  • 98
  • 150
mans
  • 17,104
  • 45
  • 172
  • 321

1 Answers1

1

See this answer.

In brief, you need to clear the ModelState before redisplaying the view, as the Html Helper will use the model state rather than the Model for its data.

Add the following statement to your controller action:

ModelState.Clear();
Community
  • 1
  • 1
Miika L.
  • 3,333
  • 1
  • 24
  • 35