Лучший способ обработать ViewModel, передав ViewModel из контроллера в View - PullRequest
1 голос
/ 26 июля 2011

Мой код:

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 голосов
/ 26 июля 2011

вероятно, формат, который вы отображаете, не соответствует подшивке по умолчанию:

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

Если вы не можете изменить формат HTML, вам нужно создать свой собственный пользовательский компоновщик

ASP.NET MVC - пользовательский механизм связывания моделей, способный обрабатывать массивы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...