Robert
Robert

Reputation: 1794

Model binding with a child object

I have a class:

public class Application
{
      ....
      public Deployment NewDeployment { get; set; }
      ....
}

I have an editor template for Deployment within the Application View folder.

The ApplicationViewModel has a SelectedApplication (of type Application), in my Index.cshtml where I use ApplicationViewModel as my Model, I have this call:

@using (Html.BeginForm("Create", "Deployment", new { @id = Model.SelectedId, 
  q = Model.Query }, FormMethod.Post, new { id = "form", role = "form" }))
{
  @Html.EditorFor(m => m.SelectedApplication.NewDeployment)
}

Which then correctly renders out the control in my DisplayTemplates\Deployment.cshtml (though, it may just be pulling the display code and nothing in relation to the NewDeployment object's contents). All is well in the world until I go to submit. At this stage everything seems good. Controller looks like:

public class DeploymentController : Controller
{
  [HttpPost]
  public ActionResult Create(Deployment NewDeployment)
  {
    Deployment.CreateDeployment(NewDeployment);
    return Redirect("/Application" + Request.Url.Query);
  }
}

However, when it goes to DeploymentController -> Create, the object has nulls for values. If I move the NewDeployment object to ApplicationViewModel, it works fine with:

@Html.EditorFor(m => m.NewDeployment)

I looked at the output name/id which was basically SelectedApplication_NewDeployment, but unfortunately changing the Create signature to similar didn't improve the results. Is it possible to model bind to a child object and if so, how?

Upvotes: 0

Views: 3175

Answers (2)

Robert
Robert

Reputation: 1794

Per Stephen Muecke's comment and with slight modifications, I was able to find how to correct it:

[HttpPost]
public ActionResult Create ([Bind(Prefix="SelectedApplication.NewDeployment")] Deployment deployment)
{
  // do things
}

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239260

Your POST action should accept the same model your form is working with, i.e.:

[HttpPost]
public ActionResult Create(ApplicationViewModel model)

Then, you'll be able to get at the deployment the same way as you did in the view:

model.SelectedApplication.NewDeployment

It was technically an accident that using @Html.EditorFor(m => m.NewDeployment) worked. The only reason it did is because the action accepted a parameter named NewDeployment. If the parameter had been named anything else, like just deployment. It would have also failed.

Upvotes: 2

Related Questions