5

我是初学者,我不知道我在这里做错了什么。在我的控制器尝试中,Numbers 对象没有值,而 FormCollection 显示数字已正确发布。

模型

    public class Numbers
{
    public int SelectedNumber;
    public int LastAttempt;
}

看法

@model PogodiBroj.Models.Numbers
@{
ViewBag.Title = "Number Guessing";
}

<h2>Guess the number</h2>

<form action="/Home/Attempt" method="post">
<div>
<label>Guess</label>
@Html.EditorFor(x => x.LastAttempt)
@Html.HiddenFor(x => x.SelectedNumber)

<input type="submit" value="Try"/>
</div>
@{ if (this.IsPost == true)
   {
       if (Model.SelectedNumber > Model.LastAttempt)
       {
           <p>My number is greater</p>
       }
       else if (Model.SelectedNumber < Model.LastAttempt)
       {
           <p>My number is lesser</p>
       }
       else
       {
           <p>Score!</p>
           @Html.ActionLink("New game", "")
       }
   }
}
</form>

控制器

    public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        Random generator = new Random();

        Numbers numbers = new Models.Numbers();
        numbers.SelectedNumber = generator.Next(100);
        numbers.LastAttempt = 0;

        return View(numbers);
    }

    public ActionResult Attempt(Numbers result)
    {
        return View("Index", result); // result has both members set to 0
    }

}
4

1 回答 1

9

您的类属性应使用 getter 和 setter 定义:

public class Numbers
{
    public int SelectedNumber { get; set; }
    public int LastAttempt { get; set; }
}
于 2013-07-25T13:11:21.237 回答