默认模型绑定器不起作用

时间:2013-07-25 13:04:26

标签: asp.net-mvc asp.net-mvc-4

我是初学者,我不知道我在这里做错了什么。在我的控制器尝试中,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
    }

}

1 个答案:

答案 0 :(得分:9)

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

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