Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default model binder not working

I'm a beginner and I don't know what I'm doing wrong here. In my controller attempt, the Numbers object doesn't have values while FormCollection shows that numbers are posted correctly.

Model

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

View

@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>

Controller

    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
    }

}
like image 936
Nezreli Avatar asked Jul 25 '13 13:07

Nezreli


1 Answers

Your class properties should be defined with getters and setters:

public class Numbers
{
    public int SelectedNumber { get; set; }
    public int LastAttempt { get; set; }
}
like image 55
Davor Zlotrg Avatar answered Oct 17 '22 04:10

Davor Zlotrg