Fria
Fria

Reputation: 119

Bind value to complex Type

I have a model like the following one:

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

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

How would I have to make the corresponding view form, to get the Model correctly binded after the post request? The user should be able to select the various Fields with checkboxes and the Model should contain the selected ones. In the Action method below, the Model's members are null.

public ActionResult XY(TestModel model){[...]}

Upvotes: 5

Views: 166

Answers (1)

Nadeem Khedr
Nadeem Khedr

Reputation: 5313

i have added to your model a Selected property

i have added an EditorTemplate to display a single Field

what will happen now when you submit, all the items will be send you can then filter all the item that have a property of Selected=true

The 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; }
}

The 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();
}

The View [/Views/Test/Index.cshtml]

@model MvcApplication2.Models.TestModel

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

The Editor Template [/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)

Upvotes: 3

Related Questions