ASP.NET MVC rendering model is not what I expect

Today I have a problem and I can’t get the weather. I understand something is wrong in ASP.NET MVC (and possibly MVC in general), or I missed something about its implementation.

So, I have a simple model hierarchy:

public class Child
{
    public Child(int notId, bool isSelected, string text)
    {
        NotId = notId;
        IsSelected = isSelected;
        Text = text;
    }

    public Child(){}

    // naming: just to make sure I do not mess with some
    // conventional infrastructure
    public int NotId { get; set; }
    public bool IsSelected { get; set; }
    public string Text { get; set; }
}

public class Parent
{
    public List<Child> Children { get; set; } 
}

Here are my HomeControllerEdit actions :

[HttpGet]
public ActionResult Edit()
{
    var parent = new Parent
                    {
                        Children = new List<Child>
                                {
                                    new Child(1, true, "a"),
                                    new Child(2, false, "b")
                                }
                    };
    return View(parent);
}

[HttpPost]
public ActionResult Edit(Parent parent)
{
    parent.Children = new List<Child>
                        {
                            new Child(4, false, "c"),
                            new Child(5, true, "d")
                        };
    return View(parent);
}

Hese is my Edit.aspxview:

<!-- Standart HTML elements ommited --> 
<% Html.BeginForm(); %>
<% for (var i = 0; i < Model.Children.Count; i++){%>
<div>
    <%=Html.LabelFor(m => m.Children[i].IsSelected)%>
    <%=Html.EditorFor(m => m.Children[i].IsSelected)%> <!-- lamda -->
    <%=Html.CheckBoxFor(m => m.Children[i].IsSelected)%> <!-- lamda -->
    <%=Html.CheckBox("A", Model.Children[i].IsSelected)%> <!-- simple -->
</div>
<% } %>

<input type="submit" value="Submit" />
<% Html.EndForm();%>

, Edit (HttpGet) Parent Child, IsSelected true false . , ​​ Edit (HttpPost), Parent Child IsSelected, false true ( HttpGet) View() .

, , , Html.EditorFor() Html.CheckBoxFor(), . , Html.EditorFor() Html.CheckBoxFor() NOT , .

-, , , ASP.NET MVC ? ? ?

.

P.S. MVC2 , - , MVC3, .

+5
2

Html.CheckBoxFor() NOT , .

.

ModelState ModelState.Clear(), , .

0

, , - , Html.EditorFor() Html.CheckBoxFor() . : Html.EditorFor() Html.CheckBoxFor() , .

, . Html modelstate , . , , :

[HttpPost]
public ActionResult Edit(Parent parent)
{
    ModelState.Remove("Children");
    parent.Children = new List<Child>
    {
        new Child(4, false, "c"),
        new Child(5, true, "d")
    };
    return View(parent);
}
+2

All Articles