3

I'm having problems binding to an object while binding to a List of objects works. Using Mvc3.1 with Tools update.

When binding to the class Form, the HttpPost-function recieves the correct model. When binding to the FormViewModel, the HttpPost-function recieves an empty model.

Are there any restrictions when binding Models containing other models?

public class FormViewModel
{
    public Form Form { get; set; }
}

public class Form
{
    public List<Section> Sections { get; set; }
}

public class Section
{
    public List<Question> Questions { get; set; }
}

public class Question
{
    public int Id { get; set; }
    public string Description { get; set; }
}

1 Answer 1

2

The name attribute of your input elements is what the binder uses as context for doing its magic. My guess is that your view contains something like this:

@model Form
@Html.EditorFor(m => m.Sections)

And your post method looks like this:

[HttpPost]
public ActionResult Function(FormViewModel formViewModel)
{
    // ...
}

If you change your view to be:

@model FormViewModel
@Html.EditorFor(m => m.Form.Sections)

And your get action to return an instance of FormViewModel, it would probably work just fine. The helpers will use the body of the lambda expression to create the name of the input element. In this case, it will create something like Form.Sections[0].Field. Then, the model binder is able to pick up on Form.Sections[] and properly initialize the FormViewModel.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.