Nigel
Nigel

Reputation: 2160

ASP MVC: Submitting a form with nested user controls

I'm fairly new to ASP MVC so go easy :).

I have a form that contains a number of user controls (partial views, as in System.Web.Mvc.ViewUserControl), each with their own view models, and some of those user controls have nested user controls within them. I intended to reuse these user controls so I built up the form using a hierarchy in this way and pass the form a parent view model that contains all the user controls' view models within it.

For example:

Parent Page (with form and ParentViewModel)
  -->ChildControl1 (uses ViewModel1 which is passed from ParentViewModel.ViewModel1 property)
  -->ChildControl2 (uses ViewModel2 which is passed from ParentViewModel.ViewModel2 property)
    -->ChildControl3 (uses ViewModel3 which is passed from ViewModel2.ViewModel3 property)

I hope this makes sense...

My question is how do I retrieve the view data when the form is submitted? It seems the view data cannot bind to the ParentViewModel:

public string Save(ParentViewModel viewData)...

as viewData.ViewModel1 and viewData.ViewModel2 are always null. Is there a way I can perform a custom binding?

Ultimately I need the form to be able to cope with a dynamic number of user controls and perform an asynchronous submission without postback. I'll cross those bridges when I come to them but I mention it now so any answer won't preclude this functionality.

Many thanks.

Upvotes: 0

Views: 368

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

For databinding to work you need to give special names to your text fields. For example in ChildControl1:

<%= Html.TextBox("ViewModel1.Property1", Model.Property1) %>

This will generate the following markup:

<input type="text" name="ViewModel1.Property1" id="ViewModel1_Property1" value="" />

And when you post to the following action:

public ActionResult Save(ParentViewModel viewData)
{
    ...
}

It will update the value of viewData.ViewData1.Property1. For binding collections you may take a look at this article.

Upvotes: 1

Related Questions