ASP.NET MVC Subform Data Not Published

This seems simple enough, but I'm missing something:

Model:

public class MainModel
{

   public SubModel oSubmodel = new Submodel();

....

}

View:

@model myApp.Models.MainModel
@using (Html.BeginForm("Index","Account", FormMethod.Post, new { id = "form"}) 
{

     @Html.LabelFor(m => m.oSubmodel.prop1

     @Html.TextBoxFor(m => m.oSubmodel.prop1

}

Controller:

 [HttpPost]
 public ActionResult Index(MainModel oModel)
 {
      ....
      string prop = oModel.prop <-----------ok
      string prop1 = oModel.oSubmodel.prop1   <----------null
  }

M.oSubmodel.prop1 data is displayed correctly in the view. When data is sent back to the controller, the MainModel values ​​are transferred correctly, however, all submodel values ​​are zero.

Anyone give an idea?

+3
source share
1 answer

Correctly. My fault. The submodel should be set as a property from the main model to bind to the correct operation in post:

So,

public class MainModel
{

   public SubModel oSubmodel = new Submodel();

....

}

becomes:

public class MainModel
{

   public SubModel oSubmodel { get; set; }

....

}

Binding then works fine. Thanks to those who answered.

+3
source

All Articles