在MVC 2中使用复杂模型

时间:2010-07-09 20:38:41

标签: asp.net-mvc

我有:
1)

public class Model
{
    public String Name { get; set; }
    public SubModel SubModel { get; set; }
}  

2)

public SubModel
{
    public String Title { get; set; }
}

3)模型型ModelViewUserControl
4)SubModel-typed SubModelViewUserControl
5)页面

我需要:
在页面 2 TextBoxes 上显示: Model.Name Model.SubModel.Title

我这样做:
1)在Page:

<% Html.RenderPartial("ModelViewUserControl", Model); %>

2)在ModelViewUserControl中:

<%= Html.TextBoxFor(m => m.Name) %>
<% Html.RenderPartial("SubModelViewUserControl", Model.SubModel); %>

3)在SubModelViewUserControl中:

<%= Html.TextBoxFor(m => m.Title) %>

结果是
在Controller的方法中,我有Model.Name ==“Bla”但Model.SubModel == null。 当然,我使用的是Html.BeginForm()。

HTML:

<input id="Name" name="Name" type="text" value="" />
<input id="Title" name="Title" type="text" value="" />

3 个答案:

答案 0 :(得分:2)

我建议您使用editor templates而不是RenderPartial,这会让您的生活更轻松:

在主视图中:

<% using (Html.BeginForm()) { %>
    <%= Html.EditorForModel() %>
    <input type="submit" value="OK" />
<% } %>

模型的编辑器模板(~/Views/Shared/EditorTemplates/Model.ascx):

<%= Html.TextBoxFor(x => x.Name) %>
<%= Html.EditorFor(x => x.SubModel) %>

SubModel的编辑器模板(~/Views/Shared/EditorTemplates/SubModel.ascx):

<%= Html.TextBoxFor(m => m.Title) %>

答案 1 :(得分:1)

确保您的两种操作方法正在使用模型的 SAME 数据类型。

您的视图可以显示如下文本框字段:

<%: Html.TextBoxFor(m => m.Name) %>
<%: Html.TextBoxFor(m => m.SubModel.Title) %>

如果您需要更多帮助,请发布您的操作方法和观点。

答案 2 :(得分:0)

以大量盐为例。我还在努力解决这个问题。

这不是解决这个问题的最简单方法,但我用于这些事情的调试方法是将action参数更改为FormCollection。然后我做:

        StringBuilder sb = new StringBuilder();
        foreach (string key in fc.Keys)
        {
            sb.Append("Key: " + key + " Value: " + fc[key]);
        }

并在debug中检查sb的值。这可能是一个糟糕的时间浪费,但这是我到目前为止偶然发现的方式。

您遇到的问题是模型绑定。 Title输入元素需要命名为[ObjectType] _ [PropertyName]。我不知道为什么Html.TextBoxFor没有处理它。