1

我有一个简单的 MVC 控制器和视图和模型(我删除了所有其他代码以找出问题)模型是一个简单的属性类:

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

视图也很简单:

@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>
      }
  }

控制器只有一种方法:

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

}

当我运行它并按下一步时,我可以看到 model.activePage 变为 2 并且它也显示在输出中(它显示 2 和第 2 页),但隐藏的值仍然是 1。实际上隐藏的值始终是 1 并且它不遵循 ActivePage 的真正价值。我还使用 HiddenFor(m=>m.ActivePage) 生成隐藏字段对其进行了测试,效果相同!问题是什么?

4

1 回答 1

1

看到这个答案

简而言之,您需要在重新显示视图之前清除 ModelState,因为 Html Helper 将使用模型状态而不是模型作为其数据。

将以下语句添加到您的控制器操作中:

ModelState.Clear();
于 2012-05-23T09:50:41.430 回答