Instead of Foreach, use For loop -
@for( int i = 0; i < Model.metric.Count; i++)
{
<div class="form-group">
@Html.Label(Model.metric[i].name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.metric[i].value, new { placeholder = "Value" })
@Html.ValidationMessageFor(m => m.metric[i].value)
</div>
<br />
</div>
}
Similarly you can go ahead for context property too.
UPDATE: Please check below sample on how to get the properties of Child Models in the Parent model. We can use FOR loop to iterate the child models. If we use For loop, we can get the values of child model on the server side without any extra work. Check below sample -
Lets say we have following Model -
public class DataModel
{
public string Name { get; set; }
public string Email { get; set; }
public List<XhrViewModel> eles { get; set; }
}
public class XhrViewModel
{
public string data1 { get; set; }
public string data2 { get; set; }
}
and then we have following controller action which will return create view -
public ActionResult CreateData()
{
DataModel m = new DataModel();
m.eles = new List<XhrViewModel>();
m.eles.Add(new XhrViewModel());
m.eles.Add(new XhrViewModel());
m.eles.Add(new XhrViewModel());
return View(m);
}
And the create view is pretty simple -
@model Rami.Vemula.Dev.Mvc.Controllers.DataModel
@{
ViewBag.Title = "CreateData";
}
<h2>CreateData</h2>
@using (Html.BeginForm("SubmitData", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DataModel</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
</div>
@for (int i = 0; i < Model.eles.Count; i++)
{
<div class="form-group">
@Html.LabelFor(model => model.eles[i].data1, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.eles[i].data1)
@Html.ValidationMessageFor(model => model.eles[i].data1)
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" id="ClickMe" class="btn btn-default" />
</div>
</div>
</div>
}
If you check in the above View, I used FOR loop instead of Foreach to render the child Model properties i.e., xhrViewModel.
And on click of the submit button, you will hit SubmitData controller action -
public ActionResult SubmitData(DataModel m)
{
return View();
}
Now when we run the application -
then on submit button, you get the values in the SubmitData controller action in this way -