简体   繁体   中英

View providing the same value to Controller

I'm trying to write a simple numbers checking program. You enter a correct next digit - it shows you next one, if not - nothing happens. In the Controller I'm trying to: set a value of variable, increment it, pass to specific View (howManyDigits). I know that I can make howManyDigits a session variable but the point here is to understand why the number is still going back to eg. "2" which was entered in View1 just after the first run of the app.

PiController:

namespace PI.Controllers
{
    public class PiController : Controller
    {
        [HttpGet]
        public ActionResult View1()
        {
            return View();
        }

        [HttpPost]
        public ActionResult View2(Pinumber number)
        {
            if (number.tabPi[number.howManyDigits] != number.numberEntered)
                number.howManyDigits++;

            return View(number);

        }

    }
}

View1:

@model PI.Models.Pinumber

@using (Html.BeginForm("View2", "Pi", FormMethod.Post))
{
    @Html.TextBoxFor(number => number.howManyDigits,new { autofocus = "autofocus"})

    <input type="submit" value="How many numbers do you know?" />
} 

In this view I have BeginForm and i'm trying to pass this variable using HiddenFor and Lambda expression back to the same Controller.

View2:

@model PI.Models.Pinumber

<div>
    3.@for (int i = 0; i < Model.howManyDigits; i++)
    {
        @Model.tabPi[i]
    }
</div>

@using (Html.BeginForm("View2", "Pi", FormMethod.Post))
{
    @Html.HiddenFor(x=> x.howManyDigits)
    @Html.TextBoxFor(x => x.numberEntered, new { autofocus = "autofocus" })

}

Model class Pinumber:

namespace PI.Models
{
    public class Pinumber
    {
        public char[] tabPi { get; set; } = new char[100000];
        public Pinumber()
        {
                for (int i = 0; i < 20; i++)
                {
                    tabPi[i] = piNumber[i];
                }
        }
        public int howManyDigits { get; set; }
        public char numberEntered { get; set; }

        public string piNumber = "141592653589793238462"

Unfortunately it's going back to Controller with an old value which i entered in other View1 which is used just to display the start site with entry number of digits that you already know - [HttpGet].

Things are not working that way.

Look, if you increment an value of some int variable, from 1 to 2 let's say, and you pass it to view. Then you want to increment it from 2 to 3, you need to send that 2 from View(from HTML code) back to the backend, and increment it there, otherwise, value is lost.

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