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
}
}
Your class properties should be defined with getters and setters:
public class Numbers
{
public int SelectedNumber { get; set; }
public int LastAttempt { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With