0

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?

5
  • Can you show the definition for your model please? Commented Apr 4, 2012 at 21:15
  • ModelClass -- Name {get;set;} Detail {get;set}. DetailClass -- Name {get;set} and ModelClass() does this.Detail=new DetailClass() Commented Apr 4, 2012 at 21:20
  • Is Detail's Name property defined as public? public string Name { get; set;}? Is Model's Detail property defined as public? public Detail Detail { get; set; }? Commented Apr 4, 2012 at 21:37
  • Ive made everything public to eliminate that as the issue.. Commented Apr 4, 2012 at 21:52
  • It is hard to tell what the issue is without more code. I have tested a simple version of this and it works just fine so I can tell you that nested model properties do in fact work with @Html.EditorFor Commented Apr 4, 2012 at 22:10

2 Answers 2

1

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.

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.