I’ve created a simple MVC application that takes information from a form and passes it to a controller
View:
@model MvcApplication1.Models.BetChargeModel
@using (Html.BeginForm())
{
<div>
@Html.TextBoxFor(m=>m.numerators[0]) / @Html.TextBoxFor(m=>m.denominators[0])
</div>
<div>
@Html.TextBoxFor(m => m.numerators[1]) / @Html.TextBoxFor(m => m.denominators[1])
</div>
<div>
<input type="submit" value="Calculate" />
</div>
}
Controller:
public ActionResult Index()
{
BetChargeModel model = new BetChargeModel();
model.numerators = new List<double>();
model.denominators = new List<double>();
model.denominators.Add(1);
model.denominators.Add(1);
model.numerators.Add(0);
model.numerators.Add(0);
return View(model);
}
[HttpPost]
public ActionResult Index(BetChargeModel model)
{
double odds1 = model.numerators[0] / model.denominators[0];
double odds = model.numerators[1] / model.denominators[1];
//other code
}
Model:
public class BetChargeModel
{
public List<double> numerators { get; set; }
public List<double> denominators { get; set; }
public double result { get; set; }
}
When I run this and try and post back information from the View the Model is coming back empty (full of null fields and zeros). Why is the data in my Textbox’s not binding to the model?
(Edit: I’ve changed the model properties and reference to Numerators, Denominators and Result but haven’t updated those here for sake of brevity)
Based on the names
numeratorsanddenominatorsit looks like you have implemented the lists as fields on the model.You should use properties instead for the model binding to work properly (which I assume that @Raphael has done).
A working model would look like this:
… and to follow to naming conventions, make sure to rename
numeratorstoNumeratorsanddenominatorstoDenominators.However, if this does not resolve your model binding issue, please elaborate and post your model implementation 🙂
— UPDATE
As you have reported that the issue still persists I will post the code I have implemented based on your own provided samples – then you can cross check to make sure everything looks right on your machine – the code shown in the following is tested and works:
Model:
View:
Controller: