开发者

Using complex model in MVC 2

I have:

1)

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

2)

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

3) Model-typed ModelViewUserControl

4) SubModel-typed SubModelViewUserControl

5) Page

I need:

Show on the Page 2 TextBoxes: for Model.Name and Model.SubModel.Title.

I do:

1) In Page:

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

2) In ModelViewUserControl:

<%= Html.TextBox开发者_如何学CFor(m => m.Name) %>
<% Html.RenderPartial("SubModelViewUserControl", Model.SubModel); %>

3) In SubModelViewUserControl:

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

Result is

In Controller's method I have Model.Name == "Bla" but Model.SubModel == null. Of course, I use Html.BeginForm().

HTML:

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

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


Instead of using RenderPartial I would recommend you using editor templates which will make your life easier:

In the main View:

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

Editor template for the model (~/Views/Shared/EditorTemplates/Model.ascx):

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

Editor template for the SubModel (~/Views/Shared/EditorTemplates/SubModel.ascx):

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


Make sure your two action methods are using the SAME data type for the model.

Your view can display the textbox fields like this:

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

If you need more help, post your action methods and your view.


Take the following with lots of salt. I'm still working through this stuff.

This isn't the easiest way to figure this out, but a debug method I use for these things is to change the action parameter to a FormCollection. Then I do:

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

And inspect the value of sb in debug. This is probably a bad time waster, but it's how I've stumbled through this so far.

The issue you're having is the model binding. The Title input element needs to be named something like [ObjectType]_[PropertyName]. I don't know why the Html.TextBoxFor is not handling that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜