Reputation: 2439
I have a form and inside it a table with input and checkbox. I coded it in razor and HTML. When I press submit button I would want to receive the row marked with the checkbox or, by default, all table with updated fields. But I am receiving a null list or the first row (it depends on my controller implementation). How can achieve it? Any ideas?
This is my code, as far as I reach:
View:
@model List<Tuto2.Models.Peliculas>
....
<div class="container">
<h1>Lista de Peliculas</h1>
@using(@Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<table class="table table-hover">
<thead>
....
</thead>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
<input type="checkbox" id="Code + @i" value="@Model[i].Code" />
</td>
<td>
<input class="pull-right" type="text" id="Titulo + @i" value="@Model[i].Titulo" />
</td>
<td>
<input class="pull-right" type="text" id="Genero + @i" value="@Model[i].Genero" />
</td>
</tr>
}
</tbody>
<tfoot>
....
</tfoot>
</table>
}
</div>
Controller:
[HttpPost]
public ActionResult Edit(List<Peliculas> c)
{
return View(Cartelera);
}
Or:
[HttpPost]
public ActionResult Edit(Peliculas p)
{
return View(Cartelera);
}
Any tip would be appreciated.
Thanks
Upvotes: 0
Views: 973
Reputation: 2439
After researching, Just for your knowlegde. Another way for returning List of checked int using html tags is given the same name to all checkboxes and collect it in the controller. Getting a List of int that were checked plus the list of string for each row at the same field.
cshtml:
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td><input class="pull-right" type="checkbox" name="code" value="@Model[i].Code" /></td>
<td><input class="pull-right" type="text" name="titulo" value="@Model[i].Titulo" /></td>
<td><input class="pull-right" type="text" name="genero" value="@Model[i].Genero" /></td>
</tr>
}
</tbody>
Controller
[HttpPost]
public ActionResult Edit(List<int> code, List<string> titulo, List<string> genero)
{
if (code != null)
{
for (int i = 0; i < Cartelera.Count; i++)
{
if (code.Contains(i))
{
Cartelera[i].Titulo = titulo[i];
Cartelera[i].Genero = genero[i];
}
}
}
return View("List1", Cartelera);
}
Upvotes: 0
Reputation: 530
@Elias please use the below lines it will help you out.
[HttpGet]
public ActionResult Edit()
{
List<Peliculas> list = new List<Peliculas>();
list.Add(new Peliculas { Code = false, Genero = "Genero1", Titulo = "Titulo1" });
list.Add(new Peliculas { Code = false, Genero = "Genero2", Titulo = "Titulo2" });
list.Add(new Peliculas { Code = false, Genero = "Genero3", Titulo = "Titulo3" });
list.Add(new Peliculas { Code = false, Genero = "Genero4", Titulo = "Titulo4" });
return View(list);
}
[HttpPost]
public ActionResult Edit(List<Peliculas> c)
{
return View(c);
}
View (body of loop):
<tr>
<td>@Html.CheckBoxFor(m => Model[i].Code)</td>
<td>@Html.TextBoxFor(m => Model[i].Titulo)</td>
<td>@Html.TextBoxFor(m => Model[i].Genero)</td>
</tr>
Upvotes: 1