0

I have this class as my model

public class Forecast
{
   public List<Test> Tests { get; set; } 

    public TimeGranularities Granularity { get; set; }

    public DateTime StartTime { get; set; }
    public string StartTimeString { get; set; }
    public int StartTimeMonth { get; set; }
    public int StartTimeYear { get; set; }

    public DateTime EndTime { get; set; }
    public string EndTimeString { get; set; }
    public int EndTimeMonth { get; set; }
    public int EndTimeYear { get; set; }

    public List<ForecastItem> ForecastItems { get; set; }
}

and this is the class for test

public class Test
{
    public int Testint { get; set; }
    public decimal Testdec { get; set; }
    public bool Testbool { get; set; }
}

My HTTPGET action result in controller

[Authorize]
    [HttpGet]
    public ActionResult Index()
    {
        var model = new Forecast
        {
            StartTimeString = DateTime.Now.AddMonths(-1).ToShortDateString(), 
            EndTimeString = DateTime.Now.ToShortDateString(),
            Tests = new List<Test>
            {
                new Test{Testint = 1, Testbool = false, Testdec = 4},
                new Test{Testint = 2, Testbool = true, Testdec = 5},
                new Test{Testint = 3, Testbool = false, Testdec = 6}
            }
        };

        return View(model);
    }

My view

@model ......Forecast

@using (Ajax.BeginForm("Index", "Forecast", new AjaxOptions { UpdateTargetId = "ForecastContainer", InsertionMode = InsertionMode.Replace, HttpMethod = "Post", OnSuccess = "calcTotals", LoadingElementId = "LoadingContainer" }))
{
<div>
    <div style="display: table-cell">
        <input type="submit" value="Generate" class="btn btn-default" />
    </div>
</div>
<br />
<div>
    @foreach (var t in Model.Tests)
    {
        @Html.EditorFor(modelItem => t.Testint)
        @Html.EditorFor(modelItem => t.Testbool)
        @Html.EditorFor(modelItem => t.Testdec)
        <br/>
    }

</div>

the view displays what i want it too. but when i submit the form and check the returned model in my POST action result in the controller, model.Tests not only doesnt save my changes, it is null.

Am i going about this the right way.

Sean Wagner
  • 121
  • 1
  • 2
  • 9
  • why you dont return your model list in vievag after in your view convert the vievag var in your list model – Enrique YC Jan 05 '15 at 21:18
  • 2
    You should try for-loop instead of foreach. There's a lengthy explanation in here: http://stackoverflow.com/questions/8894442/mvc-razor-view-nested-foreachs-model – Joonas Koski Jan 05 '15 at 21:19

1 Answers1

1

Thanks Joonas Koski for pointing me in the right direction.

What i ended up doing was changing my view to show this instead

@for (int i = 0; i < Model.Tests.Count(); i++)
    {
        @Html.CheckBoxFor(m => m.Tests[i].Testbool)
        @Html.TextBoxFor(m => m.Tests[i].Testdec)
        @Html.TextBoxFor(m => m.Tests[i].Testint)
    }
Sean Wagner
  • 121
  • 1
  • 2
  • 9