处理ViewModel从View到View传递ViewModel的最佳方法

时间:2011-07-26 11:52:34

标签: .net asp.net-mvc asp.net-mvc-3 razor

我的代码:

public ActionResult Index()
{
    IndexViewModel indexViewModel = new IndexViewModel();
    indexViewModel.Questions = GetQuestions();

    //Look here, I need to associate a answer for each question, i make a array with the number of questions, this seems a good idea?
    indexViewModel.Answers = new Answer[indexViewModel.Questions.Count];

    return View(indexViewModel);
}

[HttpPost]
public ActionResult Index(IndexViewModel indexViewModel)
{
    if (ModelState.IsValid)
    {
        //The problem is here:
        //The **Questions** property in IndexViewModel comes empty
        //and I need to associate Questions and Answers

        ...

        context.SaveChanges();

        return RedirectToAction("Index");
    } else
    {
        indexViewModel.Questions = GetQuestions();
        indexViewModel.Answers = new Answer[indexViewModel.Questions.Count];

        return View(indexViewModel);
    }
}

private IList<Question> GetQuestions()
{
    return context.Question.ToList();
}

问题在于代码注释。感谢。

更新

我的HTML:

@using (Html.BeginForm()) {
<fieldset>
    @Html.ValidationSummary(false, "Fix the erros:")

    @for (int i = 0; i < Model.Questions.Count; i++)
    {
        <div class="editor-label">
            @Html.DisplayFor(model => model.Questions[i].Description)
        </div>
        <div class="editor-field">
            @Html.LabelFor(model => model.Answers[i].Score)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Answers[i].Score)
        </div>
    }

    <p>
        <input type="submit" value="Send" />
    </p>
</fieldset>
}

1 个答案:

答案 0 :(得分:0)

可能您呈现视图的格式不符合默认绑定器:

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

如果您无法更改HTML格式,则必须创建自己的自定义活页夹

ASP.NET MVC - Custom model binder able to process arrays