I have a list, then i want to pass it to view. I use model binding method. Here is my code: Model:
public class Group
{
public string Name { get; set; }
public string GroupID { get; set; }
}
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 want to display list by group of GroupID
@using (Html.BeginForm("Index", "DisplayTable", FormMethod.Post))
{
<table>
<tr>
<td>Name</td>
<td>GroupID</td>
</tr>
@foreach(var items in Model.GroupBy(m => m.GroupID).Select(g => g.ToList())){
<tr><td colspan="2">@items.ElementAt(0).GroupID</td></tr>
for (int i = 0; i < items.Count; i++) {
<tr>
<td>@Html.TextBoxFor(m => items[i].Name)</td>
<td>@Html.TextBoxFor(m => items[i].GroupID)</td>
</tr>
}
}
</table>
<input type="submit" value="SAVE" />
}
My problem is: If I use the code above, the view display data in group correctly, but when i click button SAVE, It didn't send any data to controller, ActionResult Index(List<Group> listModel)
received a null list.
MORE EXPLANATION: I have list like this:
- NAME | GROUPID Pen; A Ink; B Pecil; A Book ; C Ruler; B NoteBook ; C
I want to display it in view like this:
- GroupID: A - Pen: A | Pencil: A
- GroupID: B - Ruler: B | Ink: B
- GroupID: C - Book: C | NoteBook: C
If i use this code in view:
<td>@Html.TextBoxFor(m => items[i].Name)</td>
<td>@Html.TextBoxFor(m => items[i].GroupID)</td>
The result in view is correct, but this cannot send data back to controller. I found that the name of each field Name
GroupID
didnt match with the name of textfield in html.
I use group by in view and i dont know what is the best way in this case: Group by in controller or in View. and What is the structure of list if I group by in controller.