문제

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