将模型中的项目列表传递回控制器

时间:2015-01-05 21:10:56

标签: c# asp.net-mvc 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; }
}

这是测试类

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

我的HTTPGET操作导致控制器

[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);
    }

我的观点

@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>

视图也会显示我想要的内容。但是当我提交表单并在控制器的POST操作结果中检查返回的模型时,model.Tests不仅不保存我的更改,它也是null。

我能以正确的方式解决这个问题。

1 个答案:

答案 0 :(得分:1)

感谢Joonas Koski指出我正确的方向。

我最终做的是改变我的观点来代替

@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)
    }