I am writing a page that allows users to enter results from test pits over a period of three days.
there is a min of two test pits and a max of ten test pits.
I initially put two pits in the View and provide add and remove buttons to allow users to add more pits.
It looks like this:
I use this javascript to add more pits:
var maxPits = 10;
var minPits = 2;
var wrapper = $(".pits");
var addButton = $(".addPit");
var delButton = $(".delPit");
var x = 2;
$(addButton).click(function (e) {
e.preventDefault();
if (x < maxPits) {
x++;
$(wrapper).append('<div class="row pit' + x + '"><div class="col-sm-1">Pit ' + x + '</div><div class="col-sm-3"><input type="number" placeholder="1.234" name="pit' + x + 'day1" id="pit' + x + 'day1"></div><div class="col-sm-3"><input type="number" placeholder="1.234" name="pit' + x + 'day2" id="pit' + x + 'day2"></div><div class="col-sm-3"><input type="number" placeholder="1.234" name="pit' + x + 'day3" id="pit' + x + 'day3"></div></div>');
updatePitCount();
} else {
alert('too many pits!');
}
});
$(delButton).click(function (e) {
e.preventDefault();
if (x > minPits) {
var lastPit = '.pit' + x;
$("div").remove(lastPit);
x--;
updatePitCount();
} else {
alert('must have a minimum of two!');
}
});
My model looks like this:
public class ResultsModel
{
public List<Pit> Pits { get; set; }
}
public class Pit
{
public int Id { get; set; }
public double Day1 { get; set; }
public double Day2 { get; set; }
public double Day3 { get; set; }
public double Mean
{
get
{
var x = 0;
var total = 0.0;
if (Day1 > 0.0) { x += 1; total += Day1; }
if (Day2 > 0.0) { x += 1; total += Day2; }
if (Day3 > 0.0) { x += 1; total += Day3; }
if(x>0) return (total) / x;
return 0.0;
}
}
}
The html is in a form that posts to a controller and I want the results from the tests to be available in the controller so that I can do some calculations on them. I am struggling to get the data from the page into the model
I want to something like this in the controller:
foreach (var pit in model.Pits)
{
var x1 = pit.Day1;
var x2 = pit.Day2;
var x3 = pit.Day3;
var m = pit.Mean;
//do something...
}
How do I get the dynamic data from the view into the controller via the model?
Any help would be appreciated.
解决方案
Razor used a spatial format of name attribute when you pass the value form view to action.
Example :
If you passing
public class ResultsModel
{
public List<Pit> Pits { get; set; }
}
model into the view and receive the same then your name attribute format must like Pits[0].Day1.