Complex Type Binding Value

I have a model similar to the following:

public class TestModel{
    public IList<Field> Fields {get; set;}
}

public class Field{
    public String Key {get; set;}
    public String Value {get; set;}
}

How can I create an appropriate presentation form to get the correct model binding after sending a request? The user should be able to select various fields using checkboxes, and the model should contain the selected ones. In the action method below, the members of the model are null.

public ActionResult XY(TestModel model){[...]}
+5
source share
1 answer

I added a property to your model Selected

I added EditorTemplateto display oneField

what happens when you send, all elements will be sent, you can then filter the whole element that has a property Selected=true

Model

public class TestModel
{
    public IList<Field> Fields { get; set; }
}

public class Field
{
    public String Key { get; set; }
    public String Value { get; set; }
    public bool Selected { get; set; }
}

Controller [TestController.cs]

public ActionResult Index()
{
    var testModel = new TestModel();
    testModel.Fields = new List<Field>
                            {
                                new Field { Key = "Choice 1" , Selected = true , Value = "1"},
                                new Field { Key = "Choice 2" , Selected = false , Value = "2"},
                                new Field { Key = "Choice 3" , Selected = false , Value = "3"}
                            };
    return View(testModel);
}

[HttpPost]
public ActionResult XY(TestModel model)
{
    var selectedFields = model.Fields.Where(f => f.Selected);

    /** Do some logic **/

    return View();
}

[/Views/Test/Index.cshtml]

@model MvcApplication2.Models.TestModel

@using(@Html.BeginForm("XY","Test"))
{
    @Html.EditorFor(m => m.Fields)
    <input type="submit" value="submit"/>
}

. [/Views/Test/EditorTemplates/Field.cshtml]

@model MvcApplication2.Models.Field
<label>
    @Html.CheckBoxFor(m =>m.Selected)
    @Model.Key 
</label>
@Html.HiddenFor(m =>m.Value)
@Html.HiddenFor(m =>m.Key)
+3

All Articles