【问题标题】:Understanding Forms in MVC: How can I populate the model from a List<>了解 MVC 中的表单:如何从 List<> 填充模型
【发布时间】:2010-10-11 11:09:12
【问题描述】:

结论在图片中,可以在底部找到


我在了解 Forms 在 MVC 中的工作方式时遇到了一些麻烦(因为我是一名 WebForms 开发人员,并且真的想在一个大项目中开始使用 MVC)

我采用了 MVC2 Web 项目并向其中添加了一个简单的 ViewModel

namespace TestForms.Models
{
    public class myFormViewModel
    {
        public myFormViewModel() { this.Options = new List<myList>(); }

        public string Name { get; set; }
        public string Email { get; set; }

        public List<myList> Options { get; set; }
    }

    public class myList
    {
        public myList() { this.Value = this.Name = ""; this.Required = false; }

        public string Name { get; set; }          
        public string Value { get; set; }      
        public string Type { get; set; }
        public bool Required { get; set; }
    }
}

创建了一个强类型视图,将一个新对象传递给视图并运行它。

当我按下提交时,它不会返回 Options 部分中的内容...我该如何绑定它

我的看法

alt text http://www.balexandre.com/temp/2010-10-11_1357.png

填写生成的表格

alt text http://www.balexandre.com/temp/2010-10-11_1353.png

当我按下 提交 时,Options 部分不会传递给模型! 我忘记了什么?

alt text http://www.balexandre.com/temp/2010-10-11_1352.png



结论

改变 View 循环来分配序号,我们现在有了

<%= Html.TextBox("model.Options[" + i + "].Value", option.Value)%>

model 是我们传递给视图的模型变量的名称 OptionsList 类型的属性名称 然后我们使用属性名

【问题讨论】:

    标签: asp.net-mvc-2 viewmodel


    【解决方案1】:

    查看您的 UI,您似乎没有将 Options 成员的数据放在上面。

    <% foreach (myList obj in Model.Options) { %>
         // Add the object to your UI. they will be serialized when the form is submitted
    <% } %>
    

    还要检查您是否将数据包含在表单元素中

    编辑:

    对不起!我没有意识到您正在填充控制器内的对象。您能在视图中显示您的代码吗?

    【讨论】:

    • 我做到了,我做到了,否则它永远不会显示AgeZipCode,因为它属于传递给索引的对象View...添加了它的图像
    • 好的!看看我前段时间在 SO 上提出的这个问题。它将为您提供使默认模型绑定器序列化复杂对象的所有步骤。 http://stackoverflow.com/questions/3800305/building-a-complex-object-step-by-step-where-to-save-it
    • 我正在尝试,但我不明白,在您的示例中,您不使用强类型视图,而是使用 ViewData/Session 来跟踪值。 我试过拥有&lt;%= Html.TextBox("Name", option.Name) %&gt;,但我得到了同样的结果,我的Options没有以任何方式填充:(
    • @balexandre:关键在于为每个属性使用完整的限定名称。如果您在某个时候查看答案,它会说:“每个字段也应该具有 ModelName.Property 的 id,以便控制器知道属性在哪里......”然后是一个代码示例......如果你命名使用完全限定名称的属性,模型绑定器将知道该属性的放置位置...
    • 谢谢,这正是我所缺少的 :) 顺序部分。非常感谢所有麻烦向我解释!太糟糕了,我不能给 +5
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多