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! :)

有帮助吗?

解决方案 2

ViewBag is supposed to be used to pass data from controller to view (dynamic alternative of ViewData).To store data between requests use session or TempData

其他提示

I couldn't see any issue with your code.

However, If you replace your code on view to below, I think this should work.

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

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

But not sure what is the difference between the Html.Hidden and directly writing the input tag.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top