【问题标题】:Best way to handle ViewModel passing ViewModel from Controller to View处理 ViewModel 将 ViewModel 从 Controller 传递到 View 的最佳方法
【发布时间】:2011-07-26 11:52:34
【问题描述】:

我的代码:

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

问题在于代码 cmets。谢谢。

更新:

我的 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>
}

【问题讨论】:

  • 这取决于你如何呈现你的 html 表单。 Asp.net mvc 默认模型绑定器接受用于绑定对象集合的特定格式。
  • MVC 模型绑定输入。您的 html 标记中没有与问题相关的输入标签。快速而肮脏的解决方案是 @Html.HiddenFor(x=>x.Questions[i].Description for each question field。
  • @Arnis 我不想要一个肮脏的解决方案,如果你能发布一个完整而干净的解决方案,我将非常感激。
  • 这很脏,因为您需要通过 HTTP 传递实体状态。我怀疑您没有在客户端对其进行修改,因此不需要首先将其传递给客户端。我的意思是 - 这不是关于回答问题(与编辑问题描述相反)吗?将问题存储在会话或数据存储中,并仅传递给客户端标识符。

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


【解决方案1】:

可能您呈现视图的格式不符合默认活页夹:

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

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

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

【讨论】:

  • 如果您查看第一个链接,它会解释您如何做到这一点
  • 好的,谢谢。在搜索更多之前有点怀疑,我必须创建一个包含问题和答案的新类?
  • 是的,你会的。否则,您可以创建自己的活页夹(查看第二个链接)
  • 太棒了,我更喜欢第一个解决方案,但是当参考带有答案的问题时,我必须使用 IdQuestion 为每个问题添加一个 HiddenField?并将 IdQuestion 放入我的新班级?
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多