Im having a weird issue with nested properties.. not sure if this is by design? When I do
@Html.EditorFor(model => model.Name)
the post works and the model is populated. When I instead do
@Html.EditorFor(model => model.Detail.Name)
model.Detail.Name is null on the post.. Is there something special i need to do for this to work?
public string Name { get; set;}
? Is Model's Detail property defined as public? public Detail Detail { get; set; }
- Travis J 2012-04-04 21:37
@Html.EditorFor
Travis J 2012-04-04 22:10
That should work. I cannot repro.
Model:
public class ModelClass
{
public string Name { get; set; }
public DetailClass Detail { get; set; }
}
public class DetailClass
{
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ModelClass
{
Name = "model name",
Detail = new DetailClass
{
Name = "detail name"
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(ModelClass model)
{
return Content(
string.Format(
"name: {0}, detail.name: {1}",
model.Name,
model.Detail.Name
)
);
}
}
View:
@model ModelClass
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Name)
@Html.EditorFor(x => x.Detail.Name)
<button type="submit">OK</button>
}
The 2 properties are correctly bound.
If you´re using EntityFramework you should include the child in the query.
For example:
public MyClass getById(int id){
return DbSet.Include(q => q.Detail).SingleOrDefault(q => q.Id == id);
}
Then when you call your Model the detail will be included. So you can use Name.Detail.Name.