nested model properties dont work with @Html.EditorFor?

Go To StackoverFlow.com

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?

2012-04-04 21:13
by XeroxDucati
Can you show the definition for your model please - Travis J 2012-04-04 21:15
ModelClass -- Name {get;set;} Detail {get;set}. DetailClass -- Name {get;set} and ModelClass() does this.Detail=new DetailClass( - XeroxDucati 2012-04-04 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; } - Travis J 2012-04-04 21:37
Ive made everything public to eliminate that as the issue. - XeroxDucati 2012-04-04 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.EditorForTravis J 2012-04-04 22:10


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.

2012-04-05 05:56
by Darin Dimitrov


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.

2017-10-08 21:07
by Felipe Marinho
Ads