简体   繁体   中英

ASP.NET MVC 4 ViewBag value incremented only once

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM