0

Hy!

I have a very interesting problem. I have a button and if a user clicks on that button it will reload that page, incrementing the value which is stored in the viewbag and write it on the screen. When the user clicks on the button, the value of the number incremented only once and I don't know why. The codes are very simple:

The controller:

public ActionResult Index()
{
         ViewBag.number= 0;
         return View();
}

[HttpPost]
public ActionResult Index(int number)
{
            ViewBag.number= number;
           return View();
}

The view:

@{

    int number= ViewBag.number;
    number++;

}
@using (Html.BeginForm("Index","Default", FormMethod.Post))
{
    @Html.Hidden("number",number)
    @Html.Display("number",number);
    <input type="submit" value="Ok" />
}

Thanks for your reply! :)

4

2 回答 2

1

我看不出您的代码有任何问题。

但是,如果您将代码替换为下面的视图,我认为这应该可行。

@using (Html.BeginForm("Index","Home", FormMethod.Post))
{

    <input type="hidden" name="number" value="@number" />
    @Html.Display("number", number)
    <input type="submit" value="Ok" />
}

但不确定 Html.Hidden 和直接编写输入标签有什么区别。

于 2013-11-05T11:09:35.183 回答
0

ViewBag应该用于将数据从控制器传递到视图(ViewData的动态替代)。要在请求之间存储数据,请使用sessionTempData

于 2013-11-05T10:17:19.183 回答