tags:

views:

40

answers:

3

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.TextBoxFor(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="" />

A: 

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.

AndrewDotHay
Action method has signature (Model model) and it successfully gets the Name property of the Model, but it don't get Model.SubModel.Title
JooLio
What does your HTML source code look like for these two fields? Does it have the entire path in the name attribute? I assume you're using Html.TextBoxFor(), go head and post a snippet of your HTML source.
AndrewDotHay
<input> tags has names (and the same Ids): "Name" and "Title".I think, right variant is "Name" and "SubModel.Title" ...
JooLio
A: 

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.

Jason
A: 

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) %>
Darin Dimitrov