0
votes

I have a list of model like this

public class Group
{
    public string Name { get; set; }
    public string GroupID { get; set; }
}

In controller:

    public ActionResult Index()
    {
        return View(ListGroup);
    }

    [HttpPost]
    public ActionResult Index(List<Group> listModel) {
        @ViewBag.Success = "Update Suceess";
        return View(listModel);

    }
    [HttpPost]
    public ActionResult Search(Group ModelSearch) { 
        List<Group> listResult = ListGroup.Where(m=>m.GroupID == ModelSearch.GroupID).ToList();
        if (ModelSearch.GroupID == null) return View("Index", ListGroup);
        return View("Index", listResult);
    }

In view i group the list as below:

        @foreach (var items in Model.GroupBy(m => m.GroupID).Select(g => g.ToList()))
        {
            <tr>
                <td colspan="2">@items.ElementAt(0).GroupID</td>
            </tr>
            foreach (var item in items) 
            {
            <tr>
                <td>@Html.TextBoxFor(m => item.GroupID)</td>
                <td>@Html.TextBoxFor(m => item.Name)</td>
            </tr>
            }
        }

It can display as groups well but i cannot get value back to controller after button submit was fired. How can i bind model to view that controller can understand and receive data from view.

1
You cannot use a foreach loop - it generates elements with duplicate name attributes which cannot be bound to a collection (does not have the necessary indexers). It also creates invalid html because of the duplicate id attributes. You need to use a for loop of a custom EditorTemplate for the type. - user3559349
can you explain more about EditorTemplate - Tran Duy Linh
This answer explains using both a for loop and a custom EditorTemplate - user3559349
as you can see, i have two loops to display this list, how can i apply that. and there are lists inside a list - Tran Duy Linh
You can use nested loops but if your trying to post back to public ActionResult Index(List<Group> listModel) its not going to work anyway. You will need to create a view model to represent want you want to display/edit in the view. - user3559349

1 Answers

0
votes

according to my understanding, you need to use a for loop rather than a foreach this will index your collections, by doing this modelbinder will work.

@for(var i = 0; i < items; i++)
{
             <tr>
                <td>@Html.TextBoxFor(m => m[i].GroupID)</td>
                <td>@Html.TextBoxFor(m => m[i].Name)</td>
            </tr>

 }