This is a migrated thread and some comments may be shown as answers.

[Solved] Nested complex models

0 Answers 137 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
dejavu
Top achievements
Rank 2
dejavu asked on 05 May 2011, 07:38 PM
Reading http://blogs.telerik.com/blogs/posts/10-09-30/using_nested_complex_objects_with_asp_net_mvc_editor_templates.aspx i tried to find a simple and reliable way to display an edit form with a model having as a property another reference type. As example:

namespace Demo.ComplexModels
{
    public class ParentModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ChildModel Child { get; set; }
    }
 
    public class ChildModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Then, in a typical controller class:

public class SimpleController
{
    public
ActionResult Create(ParentModel model)
    {
    if (ModelState.IsValid)
{
            TryUpdateModel<ParentModel>(model);
            Gateway.Create(model); // Add record to db.
 
    return RedirectToAction("Created"); // PRG, get a view with a simple confirmation message.
    }
    return View(); // Redisplay the model failing the validation.
    }
}

This is supposed to fill Child property in ParentModel instance right?. If not, and using the following view:

@{using (Html.BeginForm())
{
    <ul>
        <li>
            @Html.LabelFor(model => model.Id)
            @Html.TextBoxFor(model => model.Id)
            @Html.ValidationMessageFor(model => model.Id)
        </li>
        <li>
            @Html.LabelFor(model => model.Name)
            @Html.TextBoxFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </li>
        <li>
            @Html.LabelFor(model => model.Child)
            @Html.Telerik().DropDownListFor(model => model.Child)
                                        .DataBinding(binding =>
                                            binding.Ajax() .Select("Load", "SimpleController"))
            @Html.ValidationMessageFor(model => model.Child)
        </li>
                <li>
                   <input type="submit" value="Save" />
               </li>
    }

What could be wrong?, i'm just getting null reference in ChildModel property verytime. It's clear to me that i can always use a typical formcollection or another method, but the binder mechanism in MVC supposed to take care of this, isn't?

Thanks in advance.

dejavu.
Tags
General Discussions
Asked by
dejavu
Top achievements
Rank 2
Share this question
or